Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Jacobian(double[] params) {
++jacobianEvaluations;
final DerivativeStructure[] dsPoint = new DerivativeStructure[params.length];
final int nC = params.length;
for (int i = 0; i < nC; ++i) {
dsPoint[i] = new DerivativeStructure(nC, 1, i, params[i]);
}
final DerivativeStructure[] dsValue = jF.value(dsPoint);
final int nR = getTarget().length;
if (dsValue.length != nR) {
throw new DimensionMismatchException(dsValue.length, nR);
}
final double[][] jacobianData = new double[nR][nC];
for (int i = 0; i < nR; ++i) {
int[] orders = new int[nC];
for (int j = 0; j < nC; ++j) {
orders[j] = 1;
jacobianData[i][j] = dsValue[i].getPartialDerivative(orders);
orders[j] = 0;
}
}
return weightMatrixSqrt.multiply(MatrixUtils.createRealMatrix(jacobianData));
}
/**
* Update the residuals array and cost function value.
* @throws DimensionMismatchException if the dimension does not match the
* problem dimension.
* @throws org.apache.commons.math3.exception.TooManyEvaluationsException
* if the maximal number of evaluations is exceeded.
* @deprecated As of 3.1. Please use {@link #computeResiduals(double[])},
* {@link #computeObjectiveValue(double[])}, {@link #computeCost(double[])}
* and {@link #setCost(double)} instead.
*/
@Deprecated
protected void updateResidualsAndCost() {
objective = computeObjectiveValue(point);
final double[] res = computeResiduals(objective);
// Compute cost.
cost = computeCost(res);
// Compute weighted residuals.
final ArrayRealVector residuals = new ArrayRealVector(res);
weightedResiduals = weightMatrixSqrt.operate(residuals).toArray();
}
/**
* Computes the cost.
*
* @param residuals Residuals.
* @return the cost.
* @see #computeResiduals(double[])
* @since 3.1
*/
protected double computeCost(double[] residuals) {
final ArrayRealVector r = new ArrayRealVector(residuals);
return FastMath.sqrt(r.dotProduct(getWeight().operate(r)));
}
/**
* Get the Root Mean Square value.
* Get the Root Mean Square value, i.e. the root of the arithmetic
* mean of the square of all weighted residuals. This is related to the
* criterion that is minimized by the optimizer as follows: if
* <em>c</em> if the criterion, and <em>n</em> is the number of
* measurements, then the RMS is <em>sqrt (c/n)</em>.
*
* @return RMS value
*/
public double getRMS() {
return FastMath.sqrt(getChiSquare() / rows);
}
/**
* Get a Chi-Square-like value assuming the N residuals follow N
* distinct normal distributions centered on 0 and whose variances are
* the reciprocal of the weights.
* @return chi-square value
*/
public double getChiSquare() {
return cost * cost;
}
/**
* Gets the square-root of the weight matrix.
*
* @return the square-
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>link #getChiSquare()}), {@code n} is the number of
* observations, {@code m} is the number of parameters and {@code C} is the
* covariance matrix.
* </p>
* <p>
* See also
* <a href="http://en.wikipedia.org/wiki/Least_squares">Wikipedia</a>,
* or
* <a href="http://mathworld.wolfram.com/LeastSquaresFitting.html">MathWorld</a>,
* equations (34) and (35) for a particular case.
* </p>
*
* @return an estimate of the standard deviation of the optimized parameters
* @throws org.apache.commons.math3.linear.SingularMatrixException
* if the covariance matrix cannot be computed.
* @throws NumberIsTooSmallException if the number of degrees of freedom is not
* positive, i.e. the number of measurements is less or equal to the number of
* parameters.
* @deprecated as of version 3.1, {@link #computeSigma(double[],double)} should be used
* instead. It should be emphasized that {@code guessParametersErrors} and
* {@code computeSigma} are <em>not</em> strictly equivalent.
*/
@Deprecated
public double[] guessParametersErrors() {
if (rows <= cols) {
throw new NumberIsTooSmallException(LocalizedFormats.NO_DEGREES_OF_FREEDOM,
rows, cols, false);
}
double[] errors = new double[cols];
final double c = FastMath.sqrt(getChiSquare() / (rows - cols));
double[][] covar = computeCovariances(point, 1e-14);
for (int i = 0; i < errors.length; ++i) {
errors[i] = FastMath.sqrt(covar[i][i]) * c;
}
return errors;
}
/**
* Computes an estimate of the standard deviation of the parameters. The
* returned values are the square root of the diagonal coefficients of the
* covariance matrix, {@code sd(a[i]) ~= sqrt(C[i][i])}, where {@code a[i]}
* is the optimized value of the {@code i}-th parameter, and {@code C} is
* the covariance matrix.
*
* @param params Model parameters.
* @param covarianceSingularityThreshold Singularity threshold (see
* {@link #computeCovariances(double[],double) computeCovariances}).
* @return an estimate of the standard deviation of the optimized parameters
* @throws org.apache.commons.math3.linear.SingularMatrixException
* if the covariance matrix cannot be computed.
* @since 3.1
*/
public double[] computeSigma(double[] params,
double covarianceSingularityThreshold) {
final int nC = params.length;
final double[] sig = new double[nC];
final double[][] cov = computeCovariances(params, covarianceSingularityThreshold);
for (int i = 0; i < nC; ++i) {
sig[i] = FastMath.sqrt(cov[i][i]);
}
return sig;
}
/** {@inheritDoc}
* @deprecated As of 3.1. Please use
* {@link BaseAbstractMultivariateVectorOptimizer#optimize(int,MultivariateVectorFunction,OptimizationData[])
* optimize(int,MultivariateDifferentiableVectorFunction,OptimizationData...)}
* instead.
*/
@Override
@Deprecated
public PointVectorValuePair optimize(int maxEval,
final DifferentiableMultivariateVectorFunction f,
final double[] target, final double[]
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.util;
import java.util.Arrays;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.exception.NotFiniteNumberException;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.exception.util.Localizable;
import org.apache.commons.math3.exception.util.LocalizedFormats;
/**
* Miscellaneous utility functions.
*
* @see ArithmeticUtils
* @see Precision
* @see MathArrays
*
* @version $Id$
*/
public final class MathUtils {
/**
* 2 π.
* @since 2.1
*/
public static final double TWO_PI = 2 * FastMath.PI;
/**
* Class contains only static methods.
*/
private MathUtils() {}
/**
* Returns an integer hash code representing the given double value.
*
* @param value the value to be hashed
* @return the hash code
*/
public static int hash(double value) {
return new Double(value).hashCode();
}
/**
* Returns an integer hash code representing the given double array.
*
* @param value the value to be hashed (may be null)
* @return the hash code
* @since 1.2
*/
public static int hash(double[] value) {
return Arrays.hashCode(value);
}
/**
* Normalize an angle in a 2&pi wide interval around a center value.
* <p>This method has three main uses:</p>
* <ul>
* <li>normalize an angle between 0 and 2π:<br/>
* {@code a = MathUtils.normalizeAngle(a, FastMath.PI);}</li>
* <li>normalize an angle between -π and +π<br/>
* {@code a = MathUtils.normalizeAngle(a, 0.0);}</li>
* <li>compute the angle between two defining angular positions:<br>
* {@code angle = MathUtils.normalizeAngle(end, start) - start;}</li>
* </ul>
* <p>Note that due to numerical accuracy and since π cannot be represented
* exactly, the result interval is <em>closed</em>, it cannot be half-closed
* as would be more satisfactory in a purely mathematical view.</p>
* @param a angle to normalize
* @param center center of the desired 2π interval for the result
* @return a-2kπ with integer k and center-π <= a-2kπ <= center+π
* @since 1.2
*/
public static double normalizeAngle(double
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> a, double center) {
return a - TWO_PI * FastMath.floor((a + FastMath.PI - center) / TWO_PI);
}
/**
* <p>Reduce {@code |a - offset|} to the primary interval
* {@code [0, |period|)}.</p>
*
* <p>Specifically, the value returned is <br/>
* {@code a - |period| * floor((a - offset) / |period|) - offset}.</p>
*
* <p>If any of the parameters are {@code NaN} or infinite, the result is
* {@code NaN}.</p>
*
* @param a Value to reduce.
* @param period Period.
* @param offset Value that will be mapped to {@code 0}.
* @return the value, within the interval {@code [0 |period|)},
* that corresponds to {@code a}.
*/
public static double reduce(double a,
double period,
double offset) {
final double p = FastMath.abs(period);
return a - p * FastMath.floor((a - offset) / p) - offset;
}
/**
* Returns the first argument with the sign of the second argument.
*
* @param magnitude Magnitude of the returned value.
* @param sign Sign of the returned value.
* @return a value with magnitude equal to {@code magnitude} and with the
* same sign as the {@code sign} argument.
* @throws MathArithmeticException if {@code magnitude == Byte.MIN_VALUE}
* and {@code sign >= 0}.
*/
public static byte copySign(byte magnitude, byte sign)
throws MathArithmeticException {
if ((magnitude >= 0 && sign >= 0) ||
(magnitude < 0 && sign < 0)) { // Sign is OK.
return magnitude;
} else if (sign >= 0 &&
magnitude == Byte.MIN_VALUE) {
throw new MathArithmeticException(LocalizedFormats.OVERFLOW);
} else {
return (byte) -magnitude; // Flip sign.
}
}
/**
* Returns the first argument with the sign of the second argument.
*
* @param magnitude Magnitude of the returned value.
* @param sign Sign of the returned value.
* @return a value with magnitude equal to {@code magnitude} and with the
* same sign as the {@code sign} argument.
* @throws MathArithmeticException if {@code magnitude == Short.MIN_VALUE}
* and {@code sign >= 0}.
*/
public static short copySign(short magnitude, short sign)
throws MathArithmeticException {
if ((magnitude >= 0 && sign >= 0) ||
(magnitude < 0 && sign < 0)) { // Sign is OK.
return magnitude;
} else if (sign >= 0 &&
magnitude == Short.MIN_VALUE) {
throw new MathArithmeticException(LocalizedFormats.OVERFLOW);
} else {
return (short) -magnitude; // Flip sign.
}
}
/**
* Returns the first argument with the sign of the second argument.
*
* @param magnitude Magnitude of the returned value.
* @param sign Sign of the returned value.
* @return a value with magnitude equal to {@code magnitude} and with the
* same sign as the {@code sign} argument.
* @throws MathArithmeticException if {@code magnitude == Integer.MIN_VALUE}
* and {@code sign >= 0}.
*/
public static int copySign(int magnitude, int sign)
throws MathArithmeticException {
if ((magnitude >= 0 && sign >= 0) ||
(magnitude < 0 && sign < 0)) { // Sign is
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> "}"
* @param separator separator to use instead of the default "; "
*/
public RealVectorFormat(final String prefix, final String suffix,
final String separator) {
this(prefix, suffix, separator,
CompositeFormat.getDefaultNumberFormat());
}
/**
* Create an instance with custom prefix, suffix, separator and format
* for components.
* @param prefix prefix to use instead of the default "{"
* @param suffix suffix to use instead of the default "}"
* @param separator separator to use instead of the default "; "
* @param format the custom format for components.
*/
public RealVectorFormat(final String prefix, final String suffix,
final String separator, final NumberFormat format) {
this.prefix = prefix;
this.suffix = suffix;
this.separator = separator;
trimmedPrefix = prefix.trim();
trimmedSuffix = suffix.trim();
trimmedSeparator = separator.trim();
this.format = format;
}
/**
* Get the set of locales for which real vectors formats are available.
* <p>This is the same set as the {@link NumberFormat} set.</p>
* @return available real vector format locales.
*/
public static Locale[] getAvailableLocales() {
return NumberFormat.getAvailableLocales();
}
/**
* Get the format prefix.
* @return format prefix.
*/
public String getPrefix() {
return prefix;
}
/**
* Get the format suffix.
* @return format suffix.
*/
public String getSuffix() {
return suffix;
}
/**
* Get the format separator between components.
* @return format separator.
*/
public String getSeparator() {
return separator;
}
/**
* Get the components format.
* @return components format.
*/
public NumberFormat getFormat() {
return format;
}
/**
* Returns the default real vector format for the current locale.
* @return the default real vector format.
*/
public static RealVectorFormat getInstance() {
return getInstance(Locale.getDefault());
}
/**
* Returns the default real vector format for the given locale.
* @param locale the specific locale used by the format.
* @return the real vector format specific to the given locale.
*/
public static RealVectorFormat getInstance(final Locale locale) {
return new RealVectorFormat(CompositeFormat.getDefaultNumberFormat(locale));
}
/**
* This method calls {@link #format(RealVector,StringBuffer,FieldPosition)}.
*
* @param v RealVector object to format.
* @return a formatted vector.
*/
public String format(RealVector v) {
return format(v, new StringBuffer(), new FieldPosition(0)).toString();
}
/**
* Formats a {@link RealVector} object to produce a string.
* @param vector the object to format.
* @param toAppendTo where the text is to be appended
* @param pos On input: an alignment field, if desired. On output: the
* offsets of the alignment field
* @return the value passed in as toAppendTo.
*/
public StringBuffer format(RealVector vector, StringBuffer toAppendTo,
FieldPosition pos) {
pos.setBeginIndex(0);
pos.setEndIndex(0);
// format prefix
toAppendTo.append(prefix);
// format components
for (int i = 0; i < vector.getDimension(); ++i) {
if (i > 0) {
toAppendTo.append(separator);
}
CompositeFormat.formatDouble(vector.getEntry(i), format, toAppendTo, pos);
}
// format suffix
toAppendTo.append(suffix);
return
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.linear;
import org.apache.commons.math3.exception.DimensionMismatchException;
/**
* This class defines a linear operator operating on real ({@code double})
* vector spaces. No direct access to the coefficients of the underlying matrix
* is provided.
*
* The motivation for such an interface is well stated by
* <a href="#BARR1994">Barrett et al. (1994)</a>:
* <blockquote>
* We restrict ourselves to iterative methods, which work by repeatedly
* improving an approximate solution until it is accurate enough. These
* methods access the coefficient matrix A of the linear system only via the
* matrix-vector product y = A · x
* (and perhaps z = A<sup>T</sup> · x). Thus the user need only
* supply a subroutine for computing y (and perhaps z) given x, which permits
* full exploitation of the sparsity or other special structure of A.
* </blockquote>
* <br/>
*
* <dl>
* <dt><a name="BARR1994">Barret et al. (1994)</a></dt>
* <dd>
* R. Barrett, M. Berry, T. F. Chan, J. Demmel, J. M. Donato, J. Dongarra,
* V. Eijkhout, R. Pozo, C. Romine and H. Van der Vorst,
* <em>Templates for the Solution of Linear Systems: Building Blocks for
* Iterative Methods</em>, SIAM
* </dd>
* </dl>
*
* @version $Id$
* @since 3.0
*/
public abstract class RealLinearOperator {
/**
* Returns the dimension of the codomain of this operator.
*
* @return the number of rows of the underlying matrix
*/
public abstract int getRowDimension();
/**
* Returns the dimension of the domain of this operator.
*
* @return the number of columns of the underlying matrix
*/
public abstract int getColumnDimension();
/**
* Returns the result of multiplying {@code this} by the vector {@code x}.
*
* @param x the vector to operate on
* @return the product of {@code this} instance with {@code x}
* @throws DimensionMismatchException if the column dimension does not match
* the size of {@code x}
*/
public abstract RealVector operate(final RealVector x)
throws DimensionMismatchException;
/**
* Returns the result of multiplying the transpose of {@code this} operator
* by the vector {@code x} (optional operation). The default implementation
* throws an {@link UnsupportedOperationException}. Users overriding this
* method must also override
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>(this);
}
/**
* {@inheritDoc}
*
* @throws NumberIsTooLargeException if the total number of entries of the
* matrix is larger than {@code Integer.MAX_VALUE}.
*/
@Override
public OpenMapRealMatrix createMatrix(int rowDimension, int columnDimension)
throws NotStrictlyPositiveException, NumberIsTooLargeException {
return new OpenMapRealMatrix(rowDimension, columnDimension);
}
/** {@inheritDoc} */
@Override
public int getColumnDimension() {
return columns;
}
/**
* Compute the sum of this matrix and {@code m}.
*
* @param m Matrix to be added.
* @return {@code this} + {@code m}.
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as {@code this}.
*/
public OpenMapRealMatrix add(OpenMapRealMatrix m)
throws MatrixDimensionMismatchException {
MatrixUtils.checkAdditionCompatible(this, m);
final OpenMapRealMatrix out = new OpenMapRealMatrix(this);
for (OpenIntToDoubleHashMap.Iterator iterator = m.entries.iterator(); iterator.hasNext();) {
iterator.advance();
final int row = iterator.key() / columns;
final int col = iterator.key() - row * columns;
out.setEntry(row, col, getEntry(row, col) + iterator.value());
}
return out;
}
/** {@inheritDoc} */
@Override
public OpenMapRealMatrix subtract(final RealMatrix m)
throws MatrixDimensionMismatchException {
try {
return subtract((OpenMapRealMatrix) m);
} catch (ClassCastException cce) {
return (OpenMapRealMatrix) super.subtract(m);
}
}
/**
* Subtract {@code m} from this matrix.
*
* @param m Matrix to be subtracted.
* @return {@code this} - {@code m}.
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as {@code this}.
*/
public OpenMapRealMatrix subtract(OpenMapRealMatrix m)
throws MatrixDimensionMismatchException {
MatrixUtils.checkAdditionCompatible(this, m);
final OpenMapRealMatrix out = new OpenMapRealMatrix(this);
for (OpenIntToDoubleHashMap.Iterator iterator = m.entries.iterator(); iterator.hasNext();) {
iterator.advance();
final int row = iterator.key() / columns;
final int col = iterator.key() - row * columns;
out.setEntry(row, col, getEntry(row, col) - iterator.value());
}
return out;
}
/**
* {@inheritDoc}
*
* @throws NumberIsTooLargeException if {@code m} is an
* {@code OpenMapRealMatrix}, and the total number of entries of the product
* is larger than {@code Integer.MAX_VALUE}.
*/
@Override
public RealMatrix multiply(final RealMatrix m)
throws DimensionMismatchException, NumberIsTooLargeException {
try {
return multiply((OpenMapRealMatrix) m);
} catch (ClassCastException cce) {
MatrixUtils.checkMultiplicationCompatible(this, m);
final int outCols = m.getColumnDimension();
final BlockRealMatrix out = new BlockRealMatrix(rows, outCols);
for (OpenIntToDoubleHashMap.Iterator iterator = entries.iterator(); iterator.hasNext();) {
iterator.advance();
final double value = iterator.value();
final int key = iterator.key();
final int i = key / columns;
final int k = key % columns;
for (int j = 0; j < outCols; ++j) {
out
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>.addToEntry(i, j, value * m.getEntry(k, j));
}
}
return out;
}
}
/**
* Postmultiply this matrix by {@code m}.
*
* @param m Matrix to postmultiply by.
* @return {@code this} * {@code m}.
* @throws DimensionMismatchException if the number of rows of {@code m}
* differ from the number of columns of {@code this} matrix.
* @throws NumberIsTooLargeException if the total number of entries of the
* product is larger than {@code Integer.MAX_VALUE}.
*/
public OpenMapRealMatrix multiply(OpenMapRealMatrix m)
throws DimensionMismatchException, NumberIsTooLargeException {
// Safety check.
MatrixUtils.checkMultiplicationCompatible(this, m);
final int outCols = m.getColumnDimension();
OpenMapRealMatrix out = new OpenMapRealMatrix(rows, outCols);
for (OpenIntToDoubleHashMap.Iterator iterator = entries.iterator(); iterator.hasNext();) {
iterator.advance();
final double value = iterator.value();
final int key = iterator.key();
final int i = key / columns;
final int k = key % columns;
for (int j = 0; j < outCols; ++j) {
final int rightKey = m.computeKey(k, j);
if (m.entries.containsKey(rightKey)) {
final int outKey = out.computeKey(i, j);
final double outValue =
out.entries.get(outKey) + value * m.entries.get(rightKey);
if (outValue == 0.0) {
out.entries.remove(outKey);
} else {
out.entries.put(outKey, outValue);
}
}
}
}
return out;
}
/** {@inheritDoc} */
@Override
public double getEntry(int row, int column) throws OutOfRangeException {
MatrixUtils.checkRowIndex(this, row);
MatrixUtils.checkColumnIndex(this, column);
return entries.get(computeKey(row, column));
}
/** {@inheritDoc} */
@Override
public int getRowDimension() {
return rows;
}
/** {@inheritDoc} */
@Override
public void setEntry(int row, int column, double value)
throws OutOfRangeException {
MatrixUtils.checkRowIndex(this, row);
MatrixUtils.checkColumnIndex(this, column);
if (value == 0.0) {
entries.remove(computeKey(row, column));
} else {
entries.put(computeKey(row, column), value);
}
}
/** {@inheritDoc} */
@Override
public void addToEntry(int row, int column, double increment)
throws OutOfRangeException {
MatrixUtils.checkRowIndex(this, row);
MatrixUtils.checkColumnIndex(this, column);
final int key = computeKey(row, column);
final double value = entries.get(key) + increment;
if (value == 0.0) {
entries.remove(key);
} else {
entries.put(key, value);
}
}
/** {@inheritDoc} */
@Override
public void multiplyEntry(int row, int column, double factor)
throws OutOfRangeException {
MatrixUtils.checkRowIndex(this, row);
MatrixUtils.checkColumnIndex(this, column);
final int key = computeKey(row, column);
final double value = entries.get(key) * factor;
if (value == 0.0) {
entries.remove(key);
} else {
entries.put(
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
this.coefficients = new double[n];
System.arraycopy(c, 0, this.coefficients, 0, n);
}
/**
* Compute the value of the function for the given argument.
* <p>
* The value returned is <br/>
* <code>coefficients[n] * x^n + ... + coefficients[1] * x + coefficients[0]</code>
* </p>
*
* @param x Argument for which the function value should be computed.
* @return the value of the polynomial at the given point.
* @see UnivariateFunction#value(double)
*/
public double value(double x) {
return evaluate(coefficients, x);
}
/**
* Returns the degree of the polynomial.
*
* @return the degree of the polynomial.
*/
public int degree() {
return coefficients.length - 1;
}
/**
* Returns a copy of the coefficients array.
* <p>
* Changes made to the returned copy will not affect the coefficients of
* the polynomial.</p>
*
* @return a fresh copy of the coefficients array.
*/
public double[] getCoefficients() {
return coefficients.clone();
}
/**
* Uses Horner's Method to evaluate the polynomial with the given coefficients at
* the argument.
*
* @param coefficients Coefficients of the polynomial to evaluate.
* @param argument Input value.
* @return the value of the polynomial.
* @throws NoDataException if {@code coefficients} is empty.
* @throws NullArgumentException if {@code coefficients} is {@code null}.
*/
protected static double evaluate(double[] coefficients, double argument)
throws NullArgumentException, NoDataException {
MathUtils.checkNotNull(coefficients);
int n = coefficients.length;
if (n == 0) {
throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY);
}
double result = coefficients[n - 1];
for (int j = n - 2; j >= 0; j--) {
result = argument * result + coefficients[j];
}
return result;
}
/** {@inheritDoc}
* @since 3.1
* @throws NoDataException if {@code coefficients} is empty.
* @throws NullArgumentException if {@code coefficients} is {@code null}.
*/
public DerivativeStructure value(final DerivativeStructure t)
throws NullArgumentException, NoDataException {
MathUtils.checkNotNull(coefficients);
int n = coefficients.length;
if (n == 0) {
throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY);
}
DerivativeStructure result =
new DerivativeStructure(t.getFreeParameters(), t.getOrder(), coefficients[n - 1]);
for (int j = n - 2; j >= 0; j--) {
result = result.multiply(t).add(coefficients[j]);
}
return result;
}
/**
* Add a polynomial to the instance.
*
* @param p Polynomial to add.
* @return a new polynomial which is the sum of the instance and {@code p}.
*/
public PolynomialFunction add(final PolynomialFunction p) {
// identify the lowest degree polynomial
final int lowLength = FastMath.min(coefficients.length, p.coefficients.length);
final int highLength = FastMath.max(coefficients.length, p.coefficients.length);
// build the coefficients array
double[] newCoefficients = new double[highLength];
for (int i = 0
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>; i < lowLength; ++i) {
newCoefficients[i] = coefficients[i] + p.coefficients[i];
}
System.arraycopy((coefficients.length < p.coefficients.length) ?
p.coefficients : coefficients,
lowLength,
newCoefficients, lowLength,
highLength - lowLength);
return new PolynomialFunction(newCoefficients);
}
/**
* Subtract a polynomial from the instance.
*
* @param p Polynomial to subtract.
* @return a new polynomial which is the difference the instance minus {@code p}.
*/
public PolynomialFunction subtract(final PolynomialFunction p) {
// identify the lowest degree polynomial
int lowLength = FastMath.min(coefficients.length, p.coefficients.length);
int highLength = FastMath.max(coefficients.length, p.coefficients.length);
// build the coefficients array
double[] newCoefficients = new double[highLength];
for (int i = 0; i < lowLength; ++i) {
newCoefficients[i] = coefficients[i] - p.coefficients[i];
}
if (coefficients.length < p.coefficients.length) {
for (int i = lowLength; i < highLength; ++i) {
newCoefficients[i] = -p.coefficients[i];
}
} else {
System.arraycopy(coefficients, lowLength, newCoefficients, lowLength,
highLength - lowLength);
}
return new PolynomialFunction(newCoefficients);
}
/**
* Negate the instance.
*
* @return a new polynomial.
*/
public PolynomialFunction negate() {
double[] newCoefficients = new double[coefficients.length];
for (int i = 0; i < coefficients.length; ++i) {
newCoefficients[i] = -coefficients[i];
}
return new PolynomialFunction(newCoefficients);
}
/**
* Multiply the instance by a polynomial.
*
* @param p Polynomial to multiply by.
* @return a new polynomial.
*/
public PolynomialFunction multiply(final PolynomialFunction p) {
double[] newCoefficients = new double[coefficients.length + p.coefficients.length - 1];
for (int i = 0; i < newCoefficients.length; ++i) {
newCoefficients[i] = 0.0;
for (int j = FastMath.max(0, i + 1 - p.coefficients.length);
j < FastMath.min(coefficients.length, i + 1);
++j) {
newCoefficients[i] += coefficients[j] * p.coefficients[i-j];
}
}
return new PolynomialFunction(newCoefficients);
}
/**
* Returns the coefficients of the derivative of the polynomial with the given coefficients.
*
* @param coefficients Coefficients of the polynomial to differentiate.
* @return the coefficients of the derivative or {@code null} if coefficients has length 1.
* @throws NoDataException if {@code coefficients} is empty.
* @throws NullArgumentException if {@code coefficients} is {@code null}.
*/
protected static double[] differentiate(double[] coefficients)
throws NullArgumentException, NoDataException {
MathUtils.checkNotNull(coefficients);
int n = coefficients.length;
if (n == 0) {
throw new NoDataException(LocalizedFormats.EMPTY_POLYNOMIALS_COEFFICIENTS_ARRAY);
}
if (n == 1) {
return new double[]{0};
}
double[] result
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> = new double[n - 1];
for (int i = n - 1; i > 0; i--) {
result[i - 1] = i * coefficients[i];
}
return result;
}
/**
* Returns the derivative as a {@link PolynomialFunction}.
*
* @return the derivative polynomial.
*/
public PolynomialFunction polynomialDerivative() {
return new PolynomialFunction(differentiate(coefficients));
}
/**
* Returns the derivative as a {@link UnivariateFunction}.
*
* @return the derivative function.
*/
public UnivariateFunction derivative() {
return polynomialDerivative();
}
/**
* Returns a string representation of the polynomial.
*
* <p>The representation is user oriented. Terms are displayed lowest
* degrees first. The multiplications signs, coefficients equals to
* one and null terms are not displayed (except if the polynomial is 0,
* in which case the 0 constant term is displayed). Addition of terms
* with negative coefficients are replaced by subtraction of terms
* with positive coefficients except for the first displayed term
* (i.e. we display <code>-3</code> for a constant negative polynomial,
* but <code>1 - 3 x + x^2</code> if the negative coefficient is not
* the first one displayed).</p>
*
* @return a string representation of the polynomial.
*/
@Override
public String toString() {
StringBuilder s = new StringBuilder();
if (coefficients[0] == 0.0) {
if (coefficients.length == 1) {
return "0";
}
} else {
s.append(toString(coefficients[0]));
}
for (int i = 1; i < coefficients.length; ++i) {
if (coefficients[i] != 0) {
if (s.length() > 0) {
if (coefficients[i] < 0) {
s.append(" - ");
} else {
s.append(" + ");
}
} else {
if (coefficients[i] < 0) {
s.append("-");
}
}
double absAi = FastMath.abs(coefficients[i]);
if ((absAi - 1) != 0) {
s.append(toString(absAi));
s.append(' ');
}
s.append("x");
if (i > 1) {
s.append('^');
s.append(Integer.toString(i));
}
}
}
return s.toString();
}
/**
* Creates a string representing a coefficient, removing ".0" endings.
*
* @param coeff Coefficient.
* @return a string representation of {@code coeff}.
*/
private static String toString(double coeff) {
final String c = Double.toString(coeff);
if (c.endsWith(".0")) {
return c.substring(0, c.length() - 2);
} else {
return c;
}
}
/** {@inheritDoc} */
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(coefficients);
return result;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof PolynomialFunction)) {
return false;
}
PolynomialFunction other = (PolynomialFunction) obj;
if (!Arrays.equals(coefficients, other.coefficients)) {
return false;
}
return true;
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.linear;
import java.util.ArrayList;
import java.util.Locale;
import org.apache.commons.math3.exception.NoDataException;
import org.apache.commons.math3.exception.NotPositiveException;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.NullArgumentException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.util.MathUtils;
import org.apache.commons.math3.util.FastMath;
/**
* Basic implementation of RealMatrix methods regardless of the underlying storage.
* <p>All the methods implemented here use {@link #getEntry(int, int)} to access
* matrix elements. Derived class can provide faster implementations.</p>
*
* @version $Id$
* @since 2.0
*/
public abstract class AbstractRealMatrix
extends RealLinearOperator
implements RealMatrix {
/** Default format. */
private static final RealMatrixFormat DEFAULT_FORMAT = RealMatrixFormat.getInstance(Locale.US);
static {
// set the minimum fraction digits to 1 to keep compatibility
DEFAULT_FORMAT.getFormat().setMinimumFractionDigits(1);
}
/**
* Creates a matrix with no data
*/
protected AbstractRealMatrix() {}
/**
* Create a new RealMatrix with the supplied row and column dimensions.
*
* @param rowDimension the number of rows in the new matrix
* @param columnDimension the number of columns in the new matrix
* @throws NotStrictlyPositiveException if row or column dimension is not positive
*/
protected AbstractRealMatrix(final int rowDimension,
final int columnDimension)
throws NotStrictlyPositiveException {
if (rowDimension < 1) {
throw new NotStrictlyPositiveException(rowDimension);
}
if (columnDimension < 1) {
throw new NotStrictlyPositiveException(columnDimension);
}
}
/** {@inheritDoc} */
public RealMatrix add(RealMatrix m)
throws MatrixDimensionMismatchException {
MatrixUtils.checkAdditionCompatible(this, m);
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final RealMatrix out = createMatrix(rowCount, columnCount);
for (int row = 0; row < rowCount; ++row) {
for (int col = 0; col < columnCount; ++col) {
out.setEntry(row, col, getEntry(row, col) + m.getEntry(row, col));
}
}
return
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> out;
}
/** {@inheritDoc} */
public RealMatrix subtract(final RealMatrix m)
throws MatrixDimensionMismatchException {
MatrixUtils.checkSubtractionCompatible(this, m);
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final RealMatrix out = createMatrix(rowCount, columnCount);
for (int row = 0; row < rowCount; ++row) {
for (int col = 0; col < columnCount; ++col) {
out.setEntry(row, col, getEntry(row, col) - m.getEntry(row, col));
}
}
return out;
}
/** {@inheritDoc} */
public RealMatrix scalarAdd(final double d) {
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final RealMatrix out = createMatrix(rowCount, columnCount);
for (int row = 0; row < rowCount; ++row) {
for (int col = 0; col < columnCount; ++col) {
out.setEntry(row, col, getEntry(row, col) + d);
}
}
return out;
}
/** {@inheritDoc} */
public RealMatrix scalarMultiply(final double d) {
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final RealMatrix out = createMatrix(rowCount, columnCount);
for (int row = 0; row < rowCount; ++row) {
for (int col = 0; col < columnCount; ++col) {
out.setEntry(row, col, getEntry(row, col) * d);
}
}
return out;
}
/** {@inheritDoc} */
public RealMatrix multiply(final RealMatrix m)
throws DimensionMismatchException {
MatrixUtils.checkMultiplicationCompatible(this, m);
final int nRows = getRowDimension();
final int nCols = m.getColumnDimension();
final int nSum = getColumnDimension();
final RealMatrix out = createMatrix(nRows, nCols);
for (int row = 0; row < nRows; ++row) {
for (int col = 0; col < nCols; ++col) {
double sum = 0;
for (int i = 0; i < nSum; ++i) {
sum += getEntry(row, i) * m.getEntry(i, col);
}
out.setEntry(row, col, sum);
}
}
return out;
}
/** {@inheritDoc} */
public RealMatrix preMultiply(final RealMatrix m)
throws DimensionMismatchException {
return m.multiply(this);
}
/** {@inheritDoc} */
public RealMatrix power(final int p)
throws NotPositiveException, NonSquareMatrixException {
if (p < 0) {
throw new NotPositiveException(LocalizedFormats.NOT_POSITIVE_EXPONENT, p);
}
if (!isSquare()) {
throw new NonSquareMatrixException(getRowDimension(), getColumnDimension());
}
if (p == 0) {
return MatrixUtils.createRealIdentityMatrix(this.getRowDimension());
}
if (p == 1) {
return this.copy();
}
final int power = p - 1;
/*
* Only log_2(p) operations is used by doing as follows:
* 5^214 = 5^128 * 5^64 * 5^16 * 5^4 * 5^2
*
* In general, the same approach is used for A^p.
*/
final char[] binaryRepresentation = Integer
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>.toBinaryString(power).toCharArray();
final ArrayList<Integer> nonZeroPositions = new ArrayList<Integer>();
int maxI = -1;
for (int i = 0; i < binaryRepresentation.length; ++i) {
if (binaryRepresentation[i] == '1') {
final int pos = binaryRepresentation.length - i - 1;
nonZeroPositions.add(pos);
// The positions are taken in turn, so maxI is only changed once
if (maxI == -1) {
maxI = pos;
}
}
}
RealMatrix[] results = new RealMatrix[maxI + 1];
results[0] = this.copy();
for (int i = 1; i <= maxI; ++i) {
results[i] = results[i-1].multiply(results[i-1]);
}
RealMatrix result = this.copy();
for (Integer i : nonZeroPositions) {
result = result.multiply(results[i]);
}
return result;
}
/** {@inheritDoc} */
public double[][] getData() {
final double[][] data = new double[getRowDimension()][getColumnDimension()];
for (int i = 0; i < data.length; ++i) {
final double[] dataI = data[i];
for (int j = 0; j < dataI.length; ++j) {
dataI[j] = getEntry(i, j);
}
}
return data;
}
/** {@inheritDoc} */
public double getNorm() {
return walkInColumnOrder(new RealMatrixPreservingVisitor() {
/** Last row index. */
private double endRow;
/** Sum of absolute values on one column. */
private double columnSum;
/** Maximal sum across all columns. */
private double maxColSum;
/** {@inheritDoc} */
public void start(final int rows, final int columns,
final int startRow, final int endRow,
final int startColumn, final int endColumn) {
this.endRow = endRow;
columnSum = 0;
maxColSum = 0;
}
/** {@inheritDoc} */
public void visit(final int row, final int column, final double value) {
columnSum += FastMath.abs(value);
if (row == endRow) {
maxColSum = FastMath.max(maxColSum, columnSum);
columnSum = 0;
}
}
/** {@inheritDoc} */
public double end() {
return maxColSum;
}
});
}
/** {@inheritDoc} */
public double getFrobeniusNorm() {
return walkInOptimizedOrder(new RealMatrixPreservingVisitor() {
/** Sum of squared entries. */
private double sum;
/** {@inheritDoc} */
public void start(final int rows, final int columns,
final int startRow, final int endRow,
final int startColumn, final int endColumn) {
sum = 0;
}
/** {@inheritDoc} */
public void visit(final int row, final int column, final double value) {
sum += value * value;
}
/** {@inheritDoc} */
public double end() {
return FastMath.sqrt(sum);
}
});
}
/** {@inheritDoc} */
public RealMatrix getSubMatrix(final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
final RealMatrix subMatrix =
createMatrix(endRow - startRow + 1, end
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Column - startColumn + 1);
for (int i = startRow; i <= endRow; ++i) {
for (int j = startColumn; j <= endColumn; ++j) {
subMatrix.setEntry(i - startRow, j - startColumn, getEntry(i, j));
}
}
return subMatrix;
}
/** {@inheritDoc} */
public RealMatrix getSubMatrix(final int[] selectedRows,
final int[] selectedColumns)
throws NullArgumentException, NoDataException, OutOfRangeException {
MatrixUtils.checkSubMatrixIndex(this, selectedRows, selectedColumns);
final RealMatrix subMatrix =
createMatrix(selectedRows.length, selectedColumns.length);
subMatrix.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() {
/** {@inheritDoc} */
@Override
public double visit(final int row, final int column, final double value) {
return getEntry(selectedRows[row], selectedColumns[column]);
}
});
return subMatrix;
}
/** {@inheritDoc} */
public void copySubMatrix(final int startRow, final int endRow,
final int startColumn, final int endColumn,
final double[][] destination)
throws OutOfRangeException, NumberIsTooSmallException,
MatrixDimensionMismatchException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
final int rowsCount = endRow + 1 - startRow;
final int columnsCount = endColumn + 1 - startColumn;
if ((destination.length < rowsCount) || (destination[0].length < columnsCount)) {
throw new MatrixDimensionMismatchException(destination.length, destination[0].length,
rowsCount, columnsCount);
}
walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() {
/** Initial row index. */
private int startRow;
/** Initial column index. */
private int startColumn;
/** {@inheritDoc} */
@Override
public void start(final int rows, final int columns,
final int startRow, final int endRow,
final int startColumn, final int endColumn) {
this.startRow = startRow;
this.startColumn = startColumn;
}
/** {@inheritDoc} */
@Override
public void visit(final int row, final int column, final double value) {
destination[row - startRow][column - startColumn] = value;
}
}, startRow, endRow, startColumn, endColumn);
}
/** {@inheritDoc} */
public void copySubMatrix(int[] selectedRows, int[] selectedColumns,
double[][] destination)
throws OutOfRangeException, NullArgumentException, NoDataException,
MatrixDimensionMismatchException {
MatrixUtils.checkSubMatrixIndex(this, selectedRows, selectedColumns);
if ((destination.length < selectedRows.length) ||
(destination[0].length < selectedColumns.length)) {
throw new MatrixDimensionMismatchException(destination.length, destination[0].length,
selectedRows.length, selectedColumns.length);
}
for (int i = 0; i < selectedRows.length; i++) {
final double[] destinationI = destination[i];
for (int j = 0; j < selectedColumns.length; j++) {
destinationI[j] = getEntry(selectedRows[i], selectedColumns[j]);
}
}
}
/** {@inheritDoc} */
public void setSubMatrix(final double[][] subMatrix, final int row, final int column)
throws NoDataException, OutOfRangeException,
DimensionMismatchException, NullArgumentException {
MathUtils.checkNotNull(subMatrix);
final int nRows = subMatrix.length;
if (
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>nRows == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
}
final int nCols = subMatrix[0].length;
if (nCols == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
for (int r = 1; r < nRows; ++r) {
if (subMatrix[r].length != nCols) {
throw new DimensionMismatchException(nCols, subMatrix[r].length);
}
}
MatrixUtils.checkRowIndex(this, row);
MatrixUtils.checkColumnIndex(this, column);
MatrixUtils.checkRowIndex(this, nRows + row - 1);
MatrixUtils.checkColumnIndex(this, nCols + column - 1);
for (int i = 0; i < nRows; ++i) {
for (int j = 0; j < nCols; ++j) {
setEntry(row + i, column + j, subMatrix[i][j]);
}
}
}
/** {@inheritDoc} */
public RealMatrix getRowMatrix(final int row) throws OutOfRangeException {
MatrixUtils.checkRowIndex(this, row);
final int nCols = getColumnDimension();
final RealMatrix out = createMatrix(1, nCols);
for (int i = 0; i < nCols; ++i) {
out.setEntry(0, i, getEntry(row, i));
}
return out;
}
/** {@inheritDoc} */
public void setRowMatrix(final int row, final RealMatrix matrix)
throws OutOfRangeException, MatrixDimensionMismatchException {
MatrixUtils.checkRowIndex(this, row);
final int nCols = getColumnDimension();
if ((matrix.getRowDimension() != 1) ||
(matrix.getColumnDimension() != nCols)) {
throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
matrix.getColumnDimension(),
1, nCols);
}
for (int i = 0; i < nCols; ++i) {
setEntry(row, i, matrix.getEntry(0, i));
}
}
/** {@inheritDoc} */
public RealMatrix getColumnMatrix(final int column)
throws OutOfRangeException {
MatrixUtils.checkColumnIndex(this, column);
final int nRows = getRowDimension();
final RealMatrix out = createMatrix(nRows, 1);
for (int i = 0; i < nRows; ++i) {
out.setEntry(i, 0, getEntry(i, column));
}
return out;
}
/** {@inheritDoc} */
public void setColumnMatrix(final int column, final RealMatrix matrix)
throws OutOfRangeException, MatrixDimensionMismatchException {
MatrixUtils.checkColumnIndex(this, column);
final int nRows = getRowDimension();
if ((matrix.getRowDimension() != nRows) ||
(matrix.getColumnDimension() != 1)) {
throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
matrix.getColumnDimension(),
nRows, 1);
}
for (int i = 0; i < nRows; ++i) {
setEntry(i, column, matrix.getEntry(i, 0));
}
}
/** {@inheritDoc} */
public RealVector getRowVector(final int row)
throws OutOfRangeException {
return new ArrayRealVector(getRow(row), false);
}
/** {@inheritDoc} */
public void setRowVector(final int row, final RealVector vector)
throws OutOfRangeException, MatrixDimensionMismatchException {
MatrixUtils.checkRowIndex(
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>this, row);
final int nCols = getColumnDimension();
if (vector.getDimension() != nCols) {
throw new MatrixDimensionMismatchException(1, vector.getDimension(),
1, nCols);
}
for (int i = 0; i < nCols; ++i) {
setEntry(row, i, vector.getEntry(i));
}
}
/** {@inheritDoc} */
public RealVector getColumnVector(final int column)
throws OutOfRangeException {
return new ArrayRealVector(getColumn(column), false);
}
/** {@inheritDoc} */
public void setColumnVector(final int column, final RealVector vector)
throws OutOfRangeException, MatrixDimensionMismatchException {
MatrixUtils.checkColumnIndex(this, column);
final int nRows = getRowDimension();
if (vector.getDimension() != nRows) {
throw new MatrixDimensionMismatchException(vector.getDimension(), 1,
nRows, 1);
}
for (int i = 0; i < nRows; ++i) {
setEntry(i, column, vector.getEntry(i));
}
}
/** {@inheritDoc} */
public double[] getRow(final int row) throws OutOfRangeException {
MatrixUtils.checkRowIndex(this, row);
final int nCols = getColumnDimension();
final double[] out = new double[nCols];
for (int i = 0; i < nCols; ++i) {
out[i] = getEntry(row, i);
}
return out;
}
/** {@inheritDoc} */
public void setRow(final int row, final double[] array)
throws OutOfRangeException, MatrixDimensionMismatchException {
MatrixUtils.checkRowIndex(this, row);
final int nCols = getColumnDimension();
if (array.length != nCols) {
throw new MatrixDimensionMismatchException(1, array.length, 1, nCols);
}
for (int i = 0; i < nCols; ++i) {
setEntry(row, i, array[i]);
}
}
/** {@inheritDoc} */
public double[] getColumn(final int column) throws OutOfRangeException {
MatrixUtils.checkColumnIndex(this, column);
final int nRows = getRowDimension();
final double[] out = new double[nRows];
for (int i = 0; i < nRows; ++i) {
out[i] = getEntry(i, column);
}
return out;
}
/** {@inheritDoc} */
public void setColumn(final int column, final double[] array)
throws OutOfRangeException, MatrixDimensionMismatchException {
MatrixUtils.checkColumnIndex(this, column);
final int nRows = getRowDimension();
if (array.length != nRows) {
throw new MatrixDimensionMismatchException(array.length, 1, nRows, 1);
}
for (int i = 0; i < nRows; ++i) {
setEntry(i, column, array[i]);
}
}
/** {@inheritDoc} */
public void addToEntry(int row, int column, double increment)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
setEntry(row, column, getEntry(row, column) + increment);
}
/** {@inheritDoc} */
public void multiplyEntry(int row, int column, double factor)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
setEntry(row, column, getEntry(row, column) * factor);
}
/** {@inheritDoc} */
public Real
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Matrix transpose() {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
final RealMatrix out = createMatrix(nCols, nRows);
walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() {
/** {@inheritDoc} */
@Override
public void visit(final int row, final int column, final double value) {
out.setEntry(column, row, value);
}
});
return out;
}
/** {@inheritDoc} */
public boolean isSquare() {
return getColumnDimension() == getRowDimension();
}
/**
* Returns the number of rows of this matrix.
*
* @return the number of rows.
*/
@Override
public abstract int getRowDimension();
/**
* Returns the number of columns of this matrix.
*
* @return the number of columns.
*/
@Override
public abstract int getColumnDimension();
/** {@inheritDoc} */
public double getTrace() throws NonSquareMatrixException {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (nRows != nCols) {
throw new NonSquareMatrixException(nRows, nCols);
}
double trace = 0;
for (int i = 0; i < nRows; ++i) {
trace += getEntry(i, i);
}
return trace;
}
/** {@inheritDoc} */
public double[] operate(final double[] v)
throws DimensionMismatchException {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.length != nCols) {
throw new DimensionMismatchException(v.length, nCols);
}
final double[] out = new double[nRows];
for (int row = 0; row < nRows; ++row) {
double sum = 0;
for (int i = 0; i < nCols; ++i) {
sum += getEntry(row, i) * v[i];
}
out[row] = sum;
}
return out;
}
/** {@inheritDoc} */
@Override
public RealVector operate(final RealVector v)
throws DimensionMismatchException {
try {
return new ArrayRealVector(operate(((ArrayRealVector) v).getDataRef()), false);
} catch (ClassCastException cce) {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.getDimension() != nCols) {
throw new DimensionMismatchException(v.getDimension(), nCols);
}
final double[] out = new double[nRows];
for (int row = 0; row < nRows; ++row) {
double sum = 0;
for (int i = 0; i < nCols; ++i) {
sum += getEntry(row, i) * v.getEntry(i);
}
out[row] = sum;
}
return new ArrayRealVector(out, false);
}
}
/** {@inheritDoc} */
public double[] preMultiply(final double[] v) throws DimensionMismatchException {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.length != nRows) {
throw new DimensionMismatchException(v.length, nRows);
}
final double[] out = new double[nCols];
for (int col = 0; col < nCols; ++col) {
double sum = 0;
for (int i = 0; i < nRows; ++i) {
sum += getEntry(i, col) * v[i];
}
out[col]
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> = sum;
}
return out;
}
/** {@inheritDoc} */
public RealVector preMultiply(final RealVector v) throws DimensionMismatchException {
try {
return new ArrayRealVector(preMultiply(((ArrayRealVector) v).getDataRef()), false);
} catch (ClassCastException cce) {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.getDimension() != nRows) {
throw new DimensionMismatchException(v.getDimension(), nRows);
}
final double[] out = new double[nCols];
for (int col = 0; col < nCols; ++col) {
double sum = 0;
for (int i = 0; i < nRows; ++i) {
sum += getEntry(i, col) * v.getEntry(i);
}
out[col] = sum;
}
return new ArrayRealVector(out, false);
}
}
/** {@inheritDoc} */
public double walkInRowOrder(final RealMatrixChangingVisitor visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
final double oldValue = getEntry(row, column);
final double newValue = visitor.visit(row, column, oldValue);
setEntry(row, column, newValue);
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
visitor.visit(row, column, getEntry(row, column));
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInRowOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int row = startRow; row <= endRow; ++row) {
for (int column = startColumn; column <= endColumn; ++column) {
final double oldValue = getEntry(row, column);
final double newValue = visitor.visit(row, column, oldValue);
setEntry(row, column, newValue);
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int row = startRow; row <= endRow; ++row) {
for (int column = startColumn; column <= endColumn; ++column)
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> {
visitor.visit(row, column, getEntry(row, column));
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInColumnOrder(final RealMatrixChangingVisitor visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int column = 0; column < columns; ++column) {
for (int row = 0; row < rows; ++row) {
final double oldValue = getEntry(row, column);
final double newValue = visitor.visit(row, column, oldValue);
setEntry(row, column, newValue);
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInColumnOrder(final RealMatrixPreservingVisitor visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int column = 0; column < columns; ++column) {
for (int row = 0; row < rows; ++row) {
visitor.visit(row, column, getEntry(row, column));
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInColumnOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int column = startColumn; column <= endColumn; ++column) {
for (int row = startRow; row <= endRow; ++row) {
final double oldValue = getEntry(row, column);
final double newValue = visitor.visit(row, column, oldValue);
setEntry(row, column, newValue);
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInColumnOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int column = startColumn; column <= endColumn; ++column) {
for (int row = startRow; row <= endRow; ++row) {
visitor.visit(row, column, getEntry(row, column));
}
}
return visitor.end();
}
/** {@inheritDoc} */
public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor) {
return walkInRowOrder(visitor);
}
/** {@inheritDoc} */
public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor) {
return walkInRowOrder(visitor);
}
/** {@inheritDoc} */
public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn,
final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
return walkInRowOrder(visitor, startRow, endRow, startColumn, endColumn);
}
/** {@inheritDoc} */
public double
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
final int startColumn,
final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
return walkInRowOrder(visitor, startRow, endRow, startColumn, endColumn);
}
/**
* Get a string representation for this matrix.
* @return a string representation for this matrix
*/
@Override
public String toString() {
final StringBuilder res = new StringBuilder();
String fullClassName = getClass().getName();
String shortClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
res.append(shortClassName);
res.append(DEFAULT_FORMAT.format(this));
return res.toString();
}
/**
* Returns true iff <code>object</code> is a
* <code>RealMatrix</code> instance with the same dimensions as this
* and all corresponding matrix entries are equal.
*
* @param object the object to test equality against.
* @return true if object equals this
*/
@Override
public boolean equals(final Object object) {
if (object == this ) {
return true;
}
if (object instanceof RealMatrix == false) {
return false;
}
RealMatrix m = (RealMatrix) object;
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (m.getColumnDimension() != nCols || m.getRowDimension() != nRows) {
return false;
}
for (int row = 0; row < nRows; ++row) {
for (int col = 0; col < nCols; ++col) {
if (getEntry(row, col) != m.getEntry(row, col)) {
return false;
}
}
}
return true;
}
/**
* Computes a hashcode for the matrix.
*
* @return hashcode for matrix
*/
@Override
public int hashCode() {
int ret = 7;
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
ret = ret * 31 + nRows;
ret = ret * 31 + nCols;
for (int row = 0; row < nRows; ++row) {
for (int col = 0; col < nCols; ++col) {
ret = ret * 31 + (11 * (row+1) + 17 * (col+1)) *
MathUtils.hash(getEntry(row, col));
}
}
return ret;
}
/*
* Empty implementations of these methods are provided in order to allow for
* the use of the @Override tag with Java 1.5.
*/
/** {@inheritDoc} */
public abstract RealMatrix createMatrix(int rowDimension, int columnDimension)
throws NotStrictlyPositiveException;
/** {@inheritDoc} */
public abstract RealMatrix copy();
/** {@inheritDoc} */
public abstract double getEntry(int row, int column)
throws OutOfRangeException;
/** {@inheritDoc} */
public abstract void setEntry(int row, int column, double value)
throws OutOfRangeException;
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>ArgumentException if the array is {@code null}.
* @throws NoDataException if the array is empty.
*/
protected static <T extends FieldElement<T>> Field<T> extractField(final T[][] d)
throws NoDataException, NullArgumentException {
if (d == null) {
throw new NullArgumentException();
}
if (d.length == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
}
if (d[0].length == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
return d[0][0].getField();
}
/**
* Get the elements type from an array.
*
* @param <T> Type of the field elements.
* @param d Data array.
* @return the field to which the array elements belong.
* @throws NoDataException if array is empty.
*/
protected static <T extends FieldElement<T>> Field<T> extractField(final T[] d)
throws NoDataException {
if (d.length == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
}
return d[0].getField();
}
/** Build an array of elements.
* <p>
* Complete arrays are filled with field.getZero()
* </p>
* @param <T> Type of the field elements
* @param field field to which array elements belong
* @param rows number of rows
* @param columns number of columns (may be negative to build partial
* arrays in the same way <code>new Field[rows][]</code> works)
* @return a new array
*/
@SuppressWarnings("unchecked")
protected static <T extends FieldElement<T>> T[][] buildArray(final Field<T> field,
final int rows,
final int columns) {
if (columns < 0) {
T[] dummyRow = (T[]) Array.newInstance(field.getRuntimeClass(), 0);
return (T[][]) Array.newInstance(dummyRow.getClass(), rows);
}
T[][] array =
(T[][]) Array.newInstance(field.getRuntimeClass(), new int[] { rows, columns });
for (int i = 0; i < array.length; ++i) {
Arrays.fill(array[i], field.getZero());
}
return array;
}
/** Build an array of elements.
* <p>
* Arrays are filled with field.getZero()
* </p>
* @param <T> the type of the field elements
* @param field field to which array elements belong
* @param length of the array
* @return a new array
*/
protected static <T extends FieldElement<T>> T[] buildArray(final Field<T> field,
final int length) {
@SuppressWarnings("unchecked") // OK because field must be correct class
T[] array = (T[]) Array.newInstance(field.getRuntimeClass(), length);
Arrays.fill(array, field.getZero());
return array;
}
/** {@inheritDoc} */
public Field<T> getField() {
return field;
}
/** {@inheritDoc} */
public abstract FieldMatrix<T> createMatrix(final int rowDimension,
final int columnDimension)
throws NotStrictlyPositiveException;
/** {@inheritDoc} */
public abstract FieldMatrix<T> copy();
/** {@inheritDoc} */
public FieldMatrix<T> add(FieldMatrix<T> m)
throws MatrixDimensionMismatchException {
// safety check
checkAdditionCompatible(m);
final int rowCount = getRowDimension();
final int columnCount = getColumn
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Dimension();
final FieldMatrix<T> out = createMatrix(rowCount, columnCount);
for (int row = 0; row < rowCount; ++row) {
for (int col = 0; col < columnCount; ++col) {
out.setEntry(row, col, getEntry(row, col).add(m.getEntry(row, col)));
}
}
return out;
}
/** {@inheritDoc} */
public FieldMatrix<T> subtract(final FieldMatrix<T> m)
throws MatrixDimensionMismatchException {
// safety check
checkSubtractionCompatible(m);
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final FieldMatrix<T> out = createMatrix(rowCount, columnCount);
for (int row = 0; row < rowCount; ++row) {
for (int col = 0; col < columnCount; ++col) {
out.setEntry(row, col, getEntry(row, col).subtract(m.getEntry(row, col)));
}
}
return out;
}
/** {@inheritDoc} */
public FieldMatrix<T> scalarAdd(final T d) {
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final FieldMatrix<T> out = createMatrix(rowCount, columnCount);
for (int row = 0; row < rowCount; ++row) {
for (int col = 0; col < columnCount; ++col) {
out.setEntry(row, col, getEntry(row, col).add(d));
}
}
return out;
}
/** {@inheritDoc} */
public FieldMatrix<T> scalarMultiply(final T d) {
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final FieldMatrix<T> out = createMatrix(rowCount, columnCount);
for (int row = 0; row < rowCount; ++row) {
for (int col = 0; col < columnCount; ++col) {
out.setEntry(row, col, getEntry(row, col).multiply(d));
}
}
return out;
}
/** {@inheritDoc} */
public FieldMatrix<T> multiply(final FieldMatrix<T> m)
throws DimensionMismatchException {
// safety check
checkMultiplicationCompatible(m);
final int nRows = getRowDimension();
final int nCols = m.getColumnDimension();
final int nSum = getColumnDimension();
final FieldMatrix<T> out = createMatrix(nRows, nCols);
for (int row = 0; row < nRows; ++row) {
for (int col = 0; col < nCols; ++col) {
T sum = field.getZero();
for (int i = 0; i < nSum; ++i) {
sum = sum.add(getEntry(row, i).multiply(m.getEntry(i, col)));
}
out.setEntry(row, col, sum);
}
}
return out;
}
/** {@inheritDoc} */
public FieldMatrix<T> preMultiply(final FieldMatrix<T> m)
throws DimensionMismatchException {
return m.multiply(this);
}
/** {@inheritDoc} */
public FieldMatrix<T> power(final int p) throws NonSquareMatrixException,
NotPositiveException {
if (p < 0) {
throw new NotPositiveException(p);
}
if (!isSquare()) {
throw new NonSquareMatrixException(getRowDimension(), getColumnDimension());
}
if (p == 0) {
return Matrix
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Utils.createFieldIdentityMatrix(this.getField(), this.getRowDimension());
}
if (p == 1) {
return this.copy();
}
final int power = p - 1;
/*
* Only log_2(p) operations is used by doing as follows:
* 5^214 = 5^128 * 5^64 * 5^16 * 5^4 * 5^2
*
* In general, the same approach is used for A^p.
*/
final char[] binaryRepresentation = Integer.toBinaryString(power)
.toCharArray();
final ArrayList<Integer> nonZeroPositions = new ArrayList<Integer>();
for (int i = 0; i < binaryRepresentation.length; ++i) {
if (binaryRepresentation[i] == '1') {
final int pos = binaryRepresentation.length - i - 1;
nonZeroPositions.add(pos);
}
}
ArrayList<FieldMatrix<T>> results = new ArrayList<FieldMatrix<T>>(
binaryRepresentation.length);
results.add(0, this.copy());
for (int i = 1; i < binaryRepresentation.length; ++i) {
final FieldMatrix<T> s = results.get(i - 1);
final FieldMatrix<T> r = s.multiply(s);
results.add(i, r);
}
FieldMatrix<T> result = this.copy();
for (Integer i : nonZeroPositions) {
result = result.multiply(results.get(i));
}
return result;
}
/** {@inheritDoc} */
public T[][] getData() {
final T[][] data = buildArray(field, getRowDimension(), getColumnDimension());
for (int i = 0; i < data.length; ++i) {
final T[] dataI = data[i];
for (int j = 0; j < dataI.length; ++j) {
dataI[j] = getEntry(i, j);
}
}
return data;
}
/** {@inheritDoc} */
public FieldMatrix<T> getSubMatrix(final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws NumberIsTooSmallException, OutOfRangeException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
final FieldMatrix<T> subMatrix =
createMatrix(endRow - startRow + 1, endColumn - startColumn + 1);
for (int i = startRow; i <= endRow; ++i) {
for (int j = startColumn; j <= endColumn; ++j) {
subMatrix.setEntry(i - startRow, j - startColumn, getEntry(i, j));
}
}
return subMatrix;
}
/** {@inheritDoc} */
public FieldMatrix<T> getSubMatrix(final int[] selectedRows,
final int[] selectedColumns)
throws NoDataException, NullArgumentException, OutOfRangeException {
// safety checks
checkSubMatrixIndex(selectedRows, selectedColumns);
// copy entries
final FieldMatrix<T> subMatrix =
createMatrix(selectedRows.length, selectedColumns.length);
subMatrix.walkInOptimizedOrder(new DefaultFieldMatrixChangingVisitor<T>(field.getZero()) {
/** {@inheritDoc} */
@Override
public T visit(final int row, final int column, final T value) {
return getEntry(selectedRows[row], selectedColumns[column]);
}
});
return subMatrix;
}
/** {@inheritDoc} */
public void copySubMatrix(final int startRow, final int endRow,
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
final int startColumn, final int endColumn,
final T[][] destination)
throws MatrixDimensionMismatchException, NumberIsTooSmallException,
OutOfRangeException{
// safety checks
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
final int rowsCount = endRow + 1 - startRow;
final int columnsCount = endColumn + 1 - startColumn;
if ((destination.length < rowsCount) || (destination[0].length < columnsCount)) {
throw new MatrixDimensionMismatchException(destination.length,
destination[0].length,
rowsCount,
columnsCount);
}
// copy entries
walkInOptimizedOrder(new DefaultFieldMatrixPreservingVisitor<T>(field.getZero()) {
/** Initial row index. */
private int startRow;
/** Initial column index. */
private int startColumn;
/** {@inheritDoc} */
@Override
public void start(final int rows, final int columns,
final int startRow, final int endRow,
final int startColumn, final int endColumn) {
this.startRow = startRow;
this.startColumn = startColumn;
}
/** {@inheritDoc} */
@Override
public void visit(final int row, final int column, final T value) {
destination[row - startRow][column - startColumn] = value;
}
}, startRow, endRow, startColumn, endColumn);
}
/** {@inheritDoc} */
public void copySubMatrix(int[] selectedRows, int[] selectedColumns, T[][] destination)
throws MatrixDimensionMismatchException, NoDataException,
NullArgumentException, OutOfRangeException {
// safety checks
checkSubMatrixIndex(selectedRows, selectedColumns);
if ((destination.length < selectedRows.length) ||
(destination[0].length < selectedColumns.length)) {
throw new MatrixDimensionMismatchException(destination.length,
destination[0].length,
selectedRows.length,
selectedColumns.length);
}
// copy entries
for (int i = 0; i < selectedRows.length; i++) {
final T[] destinationI = destination[i];
for (int j = 0; j < selectedColumns.length; j++) {
destinationI[j] = getEntry(selectedRows[i], selectedColumns[j]);
}
}
}
/** {@inheritDoc} */
public void setSubMatrix(final T[][] subMatrix, final int row,
final int column)
throws DimensionMismatchException, OutOfRangeException,
NoDataException, NullArgumentException {
if (subMatrix == null) {
throw new NullArgumentException();
}
final int nRows = subMatrix.length;
if (nRows == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
}
final int nCols = subMatrix[0].length;
if (nCols == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
for (int r = 1; r < nRows; ++r) {
if (subMatrix[r].length != nCols) {
throw new DimensionMismatchException(nCols, subMatrix[r].length);
}
}
checkRowIndex(row);
checkColumnIndex(column);
checkRowIndex(nRows + row - 1);
checkColumnIndex(nCols + column - 1);
for (int i = 0; i < nRows; ++i) {
for (int j = 0; j < nCols; ++j) {
setEntry(row + i, column + j, subMatrix[i][j]);
}
}
}
/** {@inheritDoc
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>} */
public FieldMatrix<T> getRowMatrix(final int row) throws OutOfRangeException {
checkRowIndex(row);
final int nCols = getColumnDimension();
final FieldMatrix<T> out = createMatrix(1, nCols);
for (int i = 0; i < nCols; ++i) {
out.setEntry(0, i, getEntry(row, i));
}
return out;
}
/** {@inheritDoc} */
public void setRowMatrix(final int row, final FieldMatrix<T> matrix)
throws OutOfRangeException, MatrixDimensionMismatchException {
checkRowIndex(row);
final int nCols = getColumnDimension();
if ((matrix.getRowDimension() != 1) ||
(matrix.getColumnDimension() != nCols)) {
throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
matrix.getColumnDimension(),
1, nCols);
}
for (int i = 0; i < nCols; ++i) {
setEntry(row, i, matrix.getEntry(0, i));
}
}
/** {@inheritDoc} */
public FieldMatrix<T> getColumnMatrix(final int column)
throws OutOfRangeException {
checkColumnIndex(column);
final int nRows = getRowDimension();
final FieldMatrix<T> out = createMatrix(nRows, 1);
for (int i = 0; i < nRows; ++i) {
out.setEntry(i, 0, getEntry(i, column));
}
return out;
}
/** {@inheritDoc} */
public void setColumnMatrix(final int column, final FieldMatrix<T> matrix)
throws OutOfRangeException, MatrixDimensionMismatchException {
checkColumnIndex(column);
final int nRows = getRowDimension();
if ((matrix.getRowDimension() != nRows) ||
(matrix.getColumnDimension() != 1)) {
throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
matrix.getColumnDimension(),
nRows, 1);
}
for (int i = 0; i < nRows; ++i) {
setEntry(i, column, matrix.getEntry(i, 0));
}
}
/** {@inheritDoc} */
public FieldVector<T> getRowVector(final int row)
throws OutOfRangeException {
return new ArrayFieldVector<T>(field, getRow(row), false);
}
/** {@inheritDoc} */
public void setRowVector(final int row, final FieldVector<T> vector)
throws OutOfRangeException, MatrixDimensionMismatchException {
checkRowIndex(row);
final int nCols = getColumnDimension();
if (vector.getDimension() != nCols) {
throw new MatrixDimensionMismatchException(1, vector.getDimension(),
1, nCols);
}
for (int i = 0; i < nCols; ++i) {
setEntry(row, i, vector.getEntry(i));
}
}
/** {@inheritDoc} */
public FieldVector<T> getColumnVector(final int column)
throws OutOfRangeException {
return new ArrayFieldVector<T>(field, getColumn(column), false);
}
/** {@inheritDoc} */
public void setColumnVector(final int column, final FieldVector<T> vector)
throws OutOfRangeException, MatrixDimensionMismatchException {
checkColumnIndex(column);
final int nRows = getRowDimension();
if (vector.getDimension() != nRows) {
throw new MatrixDimensionMismatchException(vector.getDimension(), 1,
nRows, 1);
}
for (int i = 0; i < nRows; ++i
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>) {
setEntry(i, column, vector.getEntry(i));
}
}
/** {@inheritDoc} */
public T[] getRow(final int row) throws OutOfRangeException {
checkRowIndex(row);
final int nCols = getColumnDimension();
final T[] out = buildArray(field, nCols);
for (int i = 0; i < nCols; ++i) {
out[i] = getEntry(row, i);
}
return out;
}
/** {@inheritDoc} */
public void setRow(final int row, final T[] array)
throws OutOfRangeException, MatrixDimensionMismatchException {
checkRowIndex(row);
final int nCols = getColumnDimension();
if (array.length != nCols) {
throw new MatrixDimensionMismatchException(1, array.length, 1, nCols);
}
for (int i = 0; i < nCols; ++i) {
setEntry(row, i, array[i]);
}
}
/** {@inheritDoc} */
public T[] getColumn(final int column) throws OutOfRangeException {
checkColumnIndex(column);
final int nRows = getRowDimension();
final T[] out = buildArray(field, nRows);
for (int i = 0; i < nRows; ++i) {
out[i] = getEntry(i, column);
}
return out;
}
/** {@inheritDoc} */
public void setColumn(final int column, final T[] array)
throws OutOfRangeException, MatrixDimensionMismatchException {
checkColumnIndex(column);
final int nRows = getRowDimension();
if (array.length != nRows) {
throw new MatrixDimensionMismatchException(array.length, 1, nRows, 1);
}
for (int i = 0; i < nRows; ++i) {
setEntry(i, column, array[i]);
}
}
/** {@inheritDoc} */
public abstract T getEntry(int row, int column) throws OutOfRangeException;
/** {@inheritDoc} */
public abstract void setEntry(int row, int column, T value) throws OutOfRangeException;
/** {@inheritDoc} */
public abstract void addToEntry(int row, int column, T increment) throws OutOfRangeException;
/** {@inheritDoc} */
public abstract void multiplyEntry(int row, int column, T factor) throws OutOfRangeException;
/** {@inheritDoc} */
public FieldMatrix<T> transpose() {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
final FieldMatrix<T> out = createMatrix(nCols, nRows);
walkInOptimizedOrder(new DefaultFieldMatrixPreservingVisitor<T>(field.getZero()) {
/** {@inheritDoc} */
@Override
public void visit(final int row, final int column, final T value) {
out.setEntry(column, row, value);
}
});
return out;
}
/** {@inheritDoc} */
public boolean isSquare() {
return getColumnDimension() == getRowDimension();
}
/** {@inheritDoc} */
public abstract int getRowDimension();
/** {@inheritDoc} */
public abstract int getColumnDimension();
/** {@inheritDoc} */
public T getTrace() throws NonSquareMatrixException {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (nRows != nCols) {
throw new NonSquareMatrixException(nRows, nCols);
}
T trace = field.getZero();
for (int i = 0; i < nRows; ++i) {
trace = trace.
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>add(getEntry(i, i));
}
return trace;
}
/** {@inheritDoc} */
public T[] operate(final T[] v) throws DimensionMismatchException {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.length != nCols) {
throw new DimensionMismatchException(v.length, nCols);
}
final T[] out = buildArray(field, nRows);
for (int row = 0; row < nRows; ++row) {
T sum = field.getZero();
for (int i = 0; i < nCols; ++i) {
sum = sum.add(getEntry(row, i).multiply(v[i]));
}
out[row] = sum;
}
return out;
}
/** {@inheritDoc} */
public FieldVector<T> operate(final FieldVector<T> v)
throws DimensionMismatchException {
try {
return new ArrayFieldVector<T>(field, operate(((ArrayFieldVector<T>) v).getDataRef()), false);
} catch (ClassCastException cce) {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.getDimension() != nCols) {
throw new DimensionMismatchException(v.getDimension(), nCols);
}
final T[] out = buildArray(field, nRows);
for (int row = 0; row < nRows; ++row) {
T sum = field.getZero();
for (int i = 0; i < nCols; ++i) {
sum = sum.add(getEntry(row, i).multiply(v.getEntry(i)));
}
out[row] = sum;
}
return new ArrayFieldVector<T>(field, out, false);
}
}
/** {@inheritDoc} */
public T[] preMultiply(final T[] v) throws DimensionMismatchException {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.length != nRows) {
throw new DimensionMismatchException(v.length, nRows);
}
final T[] out = buildArray(field, nCols);
for (int col = 0; col < nCols; ++col) {
T sum = field.getZero();
for (int i = 0; i < nRows; ++i) {
sum = sum.add(getEntry(i, col).multiply(v[i]));
}
out[col] = sum;
}
return out;
}
/** {@inheritDoc} */
public FieldVector<T> preMultiply(final FieldVector<T> v)
throws DimensionMismatchException {
try {
return new ArrayFieldVector<T>(field, preMultiply(((ArrayFieldVector<T>) v).getDataRef()), false);
} catch (ClassCastException cce) {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.getDimension() != nRows) {
throw new DimensionMismatchException(v.getDimension(), nRows);
}
final T[] out = buildArray(field, nCols);
for (int col = 0; col < nCols; ++col) {
T sum = field.getZero();
for (int i = 0; i < nRows; ++i) {
sum = sum.add(getEntry(i, col).multiply(v.getEntry(i)));
}
out[col] = sum;
}
return new ArrayFieldVector<T>(field, out, false);
}
}
/** {@inheritDoc} */
public T walkInRowOrder(final FieldMatrix
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>ChangingVisitor<T> visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
final T oldValue = getEntry(row, column);
final T newValue = visitor.visit(row, column, oldValue);
setEntry(row, column, newValue);
}
}
return visitor.end();
}
/** {@inheritDoc} */
public T walkInRowOrder(final FieldMatrixPreservingVisitor<T> visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
visitor.visit(row, column, getEntry(row, column));
}
}
return visitor.end();
}
/** {@inheritDoc} */
public T walkInRowOrder(final FieldMatrixChangingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws NumberIsTooSmallException, OutOfRangeException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int row = startRow; row <= endRow; ++row) {
for (int column = startColumn; column <= endColumn; ++column) {
final T oldValue = getEntry(row, column);
final T newValue = visitor.visit(row, column, oldValue);
setEntry(row, column, newValue);
}
}
return visitor.end();
}
/** {@inheritDoc} */
public T walkInRowOrder(final FieldMatrixPreservingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws NumberIsTooSmallException, OutOfRangeException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int row = startRow; row <= endRow; ++row) {
for (int column = startColumn; column <= endColumn; ++column) {
visitor.visit(row, column, getEntry(row, column));
}
}
return visitor.end();
}
/** {@inheritDoc} */
public T walkInColumnOrder(final FieldMatrixChangingVisitor<T> visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int column = 0; column < columns; ++column) {
for (int row = 0; row < rows; ++row) {
final T oldValue = getEntry(row, column);
final T newValue = visitor.visit(row, column, oldValue);
setEntry(row, column, newValue);
}
}
return visitor.end();
}
/** {@inheritDoc} */
public T walkInColumnOrder(final FieldMatrixPreservingVisitor<T> visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>, columns, 0, rows - 1, 0, columns - 1);
for (int column = 0; column < columns; ++column) {
for (int row = 0; row < rows; ++row) {
visitor.visit(row, column, getEntry(row, column));
}
}
return visitor.end();
}
/** {@inheritDoc} */
public T walkInColumnOrder(final FieldMatrixChangingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws NumberIsTooSmallException, OutOfRangeException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int column = startColumn; column <= endColumn; ++column) {
for (int row = startRow; row <= endRow; ++row) {
final T oldValue = getEntry(row, column);
final T newValue = visitor.visit(row, column, oldValue);
setEntry(row, column, newValue);
}
}
return visitor.end();
}
/** {@inheritDoc} */
public T walkInColumnOrder(final FieldMatrixPreservingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws NumberIsTooSmallException, OutOfRangeException{
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int column = startColumn; column <= endColumn; ++column) {
for (int row = startRow; row <= endRow; ++row) {
visitor.visit(row, column, getEntry(row, column));
}
}
return visitor.end();
}
/** {@inheritDoc} */
public T walkInOptimizedOrder(final FieldMatrixChangingVisitor<T> visitor) {
return walkInRowOrder(visitor);
}
/** {@inheritDoc} */
public T walkInOptimizedOrder(final FieldMatrixPreservingVisitor<T> visitor) {
return walkInRowOrder(visitor);
}
/** {@inheritDoc} */
public T walkInOptimizedOrder(final FieldMatrixChangingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws NumberIsTooSmallException, OutOfRangeException {
return walkInRowOrder(visitor, startRow, endRow, startColumn, endColumn);
}
/** {@inheritDoc} */
public T walkInOptimizedOrder(final FieldMatrixPreservingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws NumberIsTooSmallException, OutOfRangeException {
return walkInRowOrder(visitor, startRow, endRow, startColumn, endColumn);
}
/**
* Get a string representation for this matrix.
* @return a string representation for this matrix
*/
@Override
public String toString() {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
final StringBuffer res = new StringBuffer();
String fullClassName = getClass().getName();
String shortClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
res.append(shortClassName).append("{");
for (int i = 0; i < nRows; ++i) {
if (i > 0) {
res.append(",");
}
res.append("{");
for (int j =
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>0; j < nCols; ++j) {
if (j > 0) {
res.append(",");
}
res.append(getEntry(i, j));
}
res.append("}");
}
res.append("}");
return res.toString();
}
/**
* Returns true iff <code>object</code> is a
* <code>FieldMatrix</code> instance with the same dimensions as this
* and all corresponding matrix entries are equal.
*
* @param object the object to test equality against.
* @return true if object equals this
*/
@Override
public boolean equals(final Object object) {
if (object == this ) {
return true;
}
if (object instanceof FieldMatrix<?> == false) {
return false;
}
FieldMatrix<?> m = (FieldMatrix<?>) object;
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (m.getColumnDimension() != nCols || m.getRowDimension() != nRows) {
return false;
}
for (int row = 0; row < nRows; ++row) {
for (int col = 0; col < nCols; ++col) {
if (!getEntry(row, col).equals(m.getEntry(row, col))) {
return false;
}
}
}
return true;
}
/**
* Computes a hashcode for the matrix.
*
* @return hashcode for matrix
*/
@Override
public int hashCode() {
int ret = 322562;
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
ret = ret * 31 + nRows;
ret = ret * 31 + nCols;
for (int row = 0; row < nRows; ++row) {
for (int col = 0; col < nCols; ++col) {
ret = ret * 31 + (11 * (row+1) + 17 * (col+1)) * getEntry(row, col).hashCode();
}
}
return ret;
}
/**
* Check if a row index is valid.
*
* @param row Row index to check.
* @throws OutOfRangeException if {@code index} is not valid.
*/
protected void checkRowIndex(final int row) throws OutOfRangeException {
if (row < 0 || row >= getRowDimension()) {
throw new OutOfRangeException(LocalizedFormats.ROW_INDEX,
row, 0, getRowDimension() - 1);
}
}
/**
* Check if a column index is valid.
*
* @param column Column index to check.
* @throws OutOfRangeException if {@code index} is not valid.
*/
protected void checkColumnIndex(final int column)
throws OutOfRangeException {
if (column < 0 || column >= getColumnDimension()) {
throw new OutOfRangeException(LocalizedFormats.COLUMN_INDEX,
column, 0, getColumnDimension() - 1);
}
}
/**
* Check if submatrix ranges indices are valid.
* Rows and columns are indicated counting from 0 to n-1.
*
* @param startRow Initial row index.
* @param endRow Final row index.
* @param startColumn Initial column index.
* @param endColumn Final column index.
* @throws OutOfRangeException if the indices are not valid.
* @throws NumberIsTooSmallException if {@code endRow < startRow} or
* {@code endColumn < startColumn}.
*/
protected void checkSubMatrixIndex(final int
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> startRow, final int endRow,
final int startColumn, final int endColumn)
throws NumberIsTooSmallException, OutOfRangeException {
checkRowIndex(startRow);
checkRowIndex(endRow);
if (endRow < startRow) {
throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW,
endRow, startRow, true);
}
checkColumnIndex(startColumn);
checkColumnIndex(endColumn);
if (endColumn < startColumn) {
throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_COLUMN_AFTER_FINAL_COLUMN,
endColumn, startColumn, true);
}
}
/**
* Check if submatrix ranges indices are valid.
* Rows and columns are indicated counting from 0 to n-1.
*
* @param selectedRows Array of row indices.
* @param selectedColumns Array of column indices.
* @throws NullArgumentException if the arrays are {@code null}.
* @throws NoDataException if the arrays have zero length.
* @throws OutOfRangeException if row or column selections are not valid.
*/
protected void checkSubMatrixIndex(final int[] selectedRows, final int[] selectedColumns)
throws NoDataException, NullArgumentException, OutOfRangeException {
if (selectedRows == null ||
selectedColumns == null) {
throw new NullArgumentException();
}
if (selectedRows.length == 0 ||
selectedColumns.length == 0) {
throw new NoDataException();
}
for (final int row : selectedRows) {
checkRowIndex(row);
}
for (final int column : selectedColumns) {
checkColumnIndex(column);
}
}
/**
* Check if a matrix is addition compatible with the instance.
*
* @param m Matrix to check.
* @throws MatrixDimensionMismatchException if the matrix is not
* addition-compatible with instance.
*/
protected void checkAdditionCompatible(final FieldMatrix<T> m)
throws MatrixDimensionMismatchException {
if ((getRowDimension() != m.getRowDimension()) ||
(getColumnDimension() != m.getColumnDimension())) {
throw new MatrixDimensionMismatchException(m.getRowDimension(), m.getColumnDimension(),
getRowDimension(), getColumnDimension());
}
}
/**
* Check if a matrix is subtraction compatible with the instance.
*
* @param m Matrix to check.
* @throws MatrixDimensionMismatchException if the matrix is not
* subtraction-compatible with instance.
*/
protected void checkSubtractionCompatible(final FieldMatrix<T> m)
throws MatrixDimensionMismatchException {
if ((getRowDimension() != m.getRowDimension()) ||
(getColumnDimension() != m.getColumnDimension())) {
throw new MatrixDimensionMismatchException(m.getRowDimension(), m.getColumnDimension(),
getRowDimension(), getColumnDimension());
}
}
/**
* Check if a matrix is multiplication compatible with the instance.
*
* @param m Matrix to check.
* @throws DimensionMismatchException if the matrix is not
* multiplication-compatible with instance.
*/
protected void checkMultiplicationCompatible(final FieldMatrix<T> m)
throws DimensionMismatchException {
if (getColumnDimension() != m.getRowDimension()) {
throw new DimensionMismatchException(m.getRowDimension(), getColumnDimension());
}
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
public String getPrefix() {
return prefix;
}
/**
* Get the format suffix.
* @return format suffix.
*/
public String getSuffix() {
return suffix;
}
/**
* Get the format prefix.
* @return format prefix.
*/
public String getRowPrefix() {
return rowPrefix;
}
/**
* Get the format suffix.
* @return format suffix.
*/
public String getRowSuffix() {
return rowSuffix;
}
/**
* Get the format separator between rows of the matrix.
* @return format separator for rows.
*/
public String getRowSeparator() {
return rowSeparator;
}
/**
* Get the format separator between components.
* @return format separator between components.
*/
public String getColumnSeparator() {
return columnSeparator;
}
/**
* Get the components format.
* @return components format.
*/
public NumberFormat getFormat() {
return format;
}
/**
* Returns the default real vector format for the current locale.
* @return the default real vector format.
*/
public static RealMatrixFormat getInstance() {
return getInstance(Locale.getDefault());
}
/**
* Returns the default real vector format for the given locale.
* @param locale the specific locale used by the format.
* @return the real vector format specific to the given locale.
*/
public static RealMatrixFormat getInstance(final Locale locale) {
return new RealMatrixFormat(CompositeFormat.getDefaultNumberFormat(locale));
}
/**
* This method calls {@link #format(RealMatrix,StringBuffer,FieldPosition)}.
*
* @param m RealMatrix object to format.
* @return a formatted matrix.
*/
public String format(RealMatrix m) {
return format(m, new StringBuffer(), new FieldPosition(0)).toString();
}
/**
* Formats a {@link RealMatrix} object to produce a string.
* @param matrix the object to format.
* @param toAppendTo where the text is to be appended
* @param pos On input: an alignment field, if desired. On output: the
* offsets of the alignment field
* @return the value passed in as toAppendTo.
*/
public StringBuffer format(RealMatrix matrix, StringBuffer toAppendTo,
FieldPosition pos) {
pos.setBeginIndex(0);
pos.setEndIndex(0);
// format prefix
toAppendTo.append(prefix);
// format rows
final int rows = matrix.getRowDimension();
for (int i = 0; i < rows; ++i) {
toAppendTo.append(rowPrefix);
for (int j = 0; j < matrix.getColumnDimension(); ++j) {
if (j > 0) {
toAppendTo.append(columnSeparator);
}
CompositeFormat.formatDouble(matrix.getEntry(i, j), format, toAppendTo, pos);
}
toAppendTo.append(rowSuffix);
if (i < rows - 1) {
toAppendTo.append(rowSeparator);
}
}
// format suffix
toAppendTo.append(suffix);
return toAppendTo;
}
/**
* Parse a string to produce a {@link RealMatrix} object.
*
* @param source String to parse.
* @return the parsed {@link RealMatrix} object.
* @throws MathParseException if the beginning of the specified string
* cannot be parsed.
*/
public RealMatrix parse(String source) {
final ParsePosition parsePosition = new ParsePosition(0);
final RealMatrix result = parse(source, parsePosition);
if (parsePosition.getIndex() == 0) {
throw new Math
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>DerivativeIndex(1, 1, 0)];
* double dPdXdZ = product[compiler.getPartialDerivativeIndex(1, 0, 1)];
* double dPdYdY = product[compiler.getPartialDerivativeIndex(0, 2, 0)];
* double dPdYdZ = product[compiler.getPartialDerivativeIndex(0, 1, 1)];
* double dPdZdZ = product[compiler.getPartialDerivativeIndex(0, 0, 2)];
* </p>
* @see DerivativeStructure
* @version $Id$
* @since 3.1
*/
public class DSCompiler {
/** Array of all compilers created so far. */
private static AtomicReference<DSCompiler[][]> compilers =
new AtomicReference<DSCompiler[][]>(null);
/** Number of free parameters. */
private final int parameters;
/** Derivation order. */
private final int order;
/** Number of partial derivatives (including the single 0 order derivative element). */
private final int[][] sizes;
/** Indirection array for partial derivatives. */
private final int[][] derivativesIndirection;
/** Indirection array of the lower derivative elements. */
private final int[] lowerIndirection;
/** Indirection arrays for multiplication. */
private final int[][][] multIndirection;
/** Indirection arrays for function composition. */
private final int[][][] compIndirection;
/** Private constructor, reserved for the factory method {@link #getCompiler(int, int)}.
* @param parameters number of free parameters
* @param order derivation order
* @param valueCompiler compiler for the value part
* @param derivativeCompiler compiler for the derivative part
*/
private DSCompiler(final int parameters, final int order,
final DSCompiler valueCompiler, final DSCompiler derivativeCompiler) {
this.parameters = parameters;
this.order = order;
this.sizes = compileSizes(parameters, order, valueCompiler);
this.derivativesIndirection =
compileDerivativesIndirection(parameters, order,
valueCompiler, derivativeCompiler);
this.lowerIndirection =
compileLowerIndirection(parameters, order,
valueCompiler, derivativeCompiler);
this.multIndirection =
compileMultiplicationIndirection(parameters, order,
valueCompiler, derivativeCompiler, lowerIndirection);
this.compIndirection =
compileCompositionIndirection(parameters, order,
valueCompiler, derivativeCompiler,
sizes, derivativesIndirection);
}
/** Get the compiler for number of free parameters and order.
* @param parameters number of free parameters
* @param order derivation order
* @return cached rules set
*/
public static DSCompiler getCompiler(int parameters, int order) {
// get the cached compilers
final DSCompiler[][] cache = compilers.get();
if (cache != null && cache.length > parameters && cache[parameters].length > order) {
if (cache[parameters][order] != null) {
// the compiler has already been created
return cache[parameters][order];
}
}
// we need to create more compilers
final int maxParameters = FastMath.max(parameters, cache == null ? 0 : cache.length);
final int maxOrder = FastMath.max(order, cache == null ? 0 : cache[0].length);
final DSCompiler[][] newCache = new DSCompiler[maxParameters + 1][maxOrder + 1];
if (cache != null) {
// preserve the already created compilers
for (int i = 0; i < cache.length; ++i) {
System.arraycopy(cache[i], 0, newCache[i], 0, cache[i].length);
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> }
}
// create the array in increasing diagonal order
for (int diag = 0; diag <= parameters + order; ++diag) {
for (int o = FastMath.max(0, diag - parameters); o <= FastMath.min(order, diag); ++o) {
final int p = diag - o;
if (newCache[p][o] == null) {
final DSCompiler valueCompiler = (p == 0) ? null : newCache[p - 1][o];
final DSCompiler derivativeCompiler = (o == 0) ? null : newCache[p][o - 1];
newCache[p][o] = new DSCompiler(p, o, valueCompiler, derivativeCompiler);
}
}
}
// atomically reset the cached compilers array
compilers.compareAndSet(cache, newCache);
return newCache[parameters][order];
}
/** Compile the sizes array.
* @param parameters number of free parameters
* @param order derivation order
* @param valueCompiler compiler for the value part
* @return sizes array
*/
private static int[][] compileSizes(final int parameters, final int order,
final DSCompiler valueCompiler) {
final int[][] sizes = new int[parameters + 1][order + 1];
if (parameters == 0) {
Arrays.fill(sizes[0], 1);
} else {
System.arraycopy(valueCompiler.sizes, 0, sizes, 0, parameters);
sizes[parameters][0] = 1;
for (int i = 0; i < order; ++i) {
sizes[parameters][i + 1] = sizes[parameters][i] + sizes[parameters - 1][i + 1];
}
}
return sizes;
}
/** Compile the derivatives indirection array.
* @param parameters number of free parameters
* @param order derivation order
* @param valueCompiler compiler for the value part
* @param derivativeCompiler compiler for the derivative part
* @return derivatives indirection array
*/
private static int[][] compileDerivativesIndirection(final int parameters, final int order,
final DSCompiler valueCompiler,
final DSCompiler derivativeCompiler) {
if (parameters == 0 || order == 0) {
return new int[1][parameters];
}
final int vSize = valueCompiler.derivativesIndirection.length;
final int dSize = derivativeCompiler.derivativesIndirection.length;
final int[][] derivativesIndirection = new int[vSize + dSize][parameters];
// set up the indices for the value part
for (int i = 0; i < vSize; ++i) {
// copy the first indices, the last one remaining set to 0
System.arraycopy(valueCompiler.derivativesIndirection[i], 0,
derivativesIndirection[i], 0,
parameters - 1);
}
// set up the indices for the derivative part
for (int i = 0; i < dSize; ++i) {
// copy the indices
System.arraycopy(derivativeCompiler.derivativesIndirection[i], 0,
derivativesIndirection[vSize + i], 0,
parameters);
// increment the derivation order for the last parameter
derivativesIndirection[vSize + i][parameters - 1]++;
}
return derivativesIndirection;
}
/** Compile the lower derivatives indirection array.
* <p>
* This indirection array contains the indices of all elements
* except derivatives for last derivation order.
* </p>
* @param parameters number of free parameters
* @param order derivation order
* @param valueCompiler compiler for the value part
* @param derivative
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>>
* @param orders derivation orders with respect to each parameter
* @return index of the partial derivative
* @exception DimensionMismatchException if the numbers of parameters does not
* match the instance
* @exception NumberIsTooLargeException if sum of derivation orders is larger
* than the instance limits
* @see #getPartialDerivativeOrders(int)
*/
public int getPartialDerivativeIndex(final int ... orders)
throws DimensionMismatchException, NumberIsTooLargeException {
// safety check
if (orders.length != getFreeParameters()) {
throw new DimensionMismatchException(orders.length, getFreeParameters());
}
return getPartialDerivativeIndex(parameters, order, sizes, orders);
}
/** Get the index of a partial derivative in an array.
* @param parameters number of free parameters
* @param order derivation order
* @param sizes sizes array
* @param orders derivation orders with respect to each parameter
* (the lenght of this array must match the number of parameters)
* @return index of the partial derivative
* @exception NumberIsTooLargeException if sum of derivation orders is larger
* than the instance limits
*/
private static int getPartialDerivativeIndex(final int parameters, final int order,
final int[][] sizes, final int ... orders)
throws NumberIsTooLargeException {
// the value is obtained by diving into the recursive Dan Kalman's structure
// this is theorem 2 of his paper, with recursion replaced by iteration
int index = 0;
int m = order;
int ordersSum = 0;
for (int i = parameters - 1; i >= 0; --i) {
// derivative order for current free parameter
int derivativeOrder = orders[i];
// safety check
ordersSum += derivativeOrder;
if (ordersSum > order) {
throw new NumberIsTooLargeException(ordersSum, order, true);
}
while (derivativeOrder-- > 0) {
// as long as we differentiate according to current free parameter,
// we have to skip the value part and dive into the derivative part
// so we add the size of the value part to the base index
index += sizes[i][m--];
}
}
return index;
}
/** Convert an index from one (parameters, order) structure to another.
* @param index index of a partial derivative in source derivative structure
* @param srcP number of free parameters in source derivative structure
* @param srcDerivativesIndirection derivatives indirection array for the source
* derivative structure
* @param destP number of free parameters in destination derivative structure
* @param destO derivation order in destination derivative structure
* @param destSizes sizes array for the destination derivative structure
* @return index of the partial derivative with the <em>same</em> characteristics
* in destination derivative structure
*/
private static int convertIndex(final int index,
final int srcP, final int[][] srcDerivativesIndirection,
final int destP, final int destO, final int[][] destSizes) {
int[] orders = new int[destP];
System.arraycopy(srcDerivativesIndirection[index], 0, orders, 0, FastMath.min(srcP, destP));
return getPartialDerivativeIndex(destP, destO, destSizes, orders);
}
/** Get the derivation orders for a specific index in the array.
* <p>
* This method is the inverse of {@link #getPartialDerivativeIndex(int...)}.
* </p>
* @param index of the partial derivative
* @return orders derivation orders with respect to each parameter
* @see #getPartialDerivativeIndex(int...)
*/
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> 0; i < multIndirection.length; ++i) {
final int[][] mappingI = multIndirection[i];
double r = 0;
for (int j = 0; j < mappingI.length; ++j) {
r += mappingI[j][0] *
lhs[lhsOffset + mappingI[j][1]] *
rhs[rhsOffset + mappingI[j][2]];
}
result[resultOffset + i] = r;
}
}
/** Perform division of two derivative structures.
* @param lhs array holding left hand side of division
* @param lhsOffset offset of the left hand side in its array
* @param rhs array right hand side of division
* @param rhsOffset offset of the right hand side in its array
* @param result array where result must be stored (for
* division the result array <em>cannot</em> be one of
* the input arrays)
* @param resultOffset offset of the result in its array
*/
public void divide(final double[] lhs, final int lhsOffset,
final double[] rhs, final int rhsOffset,
final double[] result, final int resultOffset) {
final double[] reciprocal = new double[getSize()];
pow(rhs, lhsOffset, -1, reciprocal, 0);
multiply(lhs, lhsOffset, reciprocal, 0, result, resultOffset);
}
/** Perform remainder of two derivative structures.
* @param lhs array holding left hand side of remainder
* @param lhsOffset offset of the left hand side in its array
* @param rhs array right hand side of remainder
* @param rhsOffset offset of the right hand side in its array
* @param result array where result must be stored (it may be
* one of the input arrays)
* @param resultOffset offset of the result in its array
*/
public void remainder(final double[] lhs, final int lhsOffset,
final double[] rhs, final int rhsOffset,
final double[] result, final int resultOffset) {
// compute k such that lhs % rhs = lhs - k rhs
final double rem = lhs[lhsOffset] % rhs[rhsOffset];
final double k = FastMath.rint((lhs[lhsOffset] - rem) / rhs[rhsOffset]);
// set up value
result[resultOffset] = rem;
// set up partial derivatives
for (int i = 1; i < getSize(); ++i) {
result[resultOffset + i] = lhs[lhsOffset + i] - k * rhs[rhsOffset + i];
}
}
/** Compute power of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param p power to apply
* @param result array where result must be stored (for
* power the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void pow(final double[] operand, final int operandOffset, final double p,
final double[] result, final int resultOffset) {
// create the function value and derivatives
// [x^p, px^(p-1), p(p-1)x^(p-2), ... ]
double[] function = new double[1 + order];
double xk = FastMath.pow(operand[operandOffset], p - order);
for (int i = order; i > 0; --i) {
function[i] = xk;
xk *= operand[operandOffset];
}
function[0] = xk;
double coefficient = p;
for (int i = 1; i <=
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> order; ++i) {
function[i] *= coefficient;
coefficient *= p - i;
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute integer power of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param n power to apply
* @param result array where result must be stored (for
* power the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void pow(final double[] operand, final int operandOffset, final int n,
final double[] result, final int resultOffset) {
if (n == 0) {
// special case, x^0 = 1 for all x
result[resultOffset] = 1.0;
Arrays.fill(result, resultOffset + 1, resultOffset + getSize(), 0);
return;
}
// create the power function value and derivatives
// [x^n, nx^(n-1), n(n-1)x^(n-2), ... ]
double[] function = new double[1 + order];
if (n > 0) {
// strictly positive power
final int maxOrder = FastMath.min(order, n);
double xk = FastMath.pow(operand[operandOffset], n - maxOrder);
for (int i = maxOrder; i > 0; --i) {
function[i] = xk;
xk *= operand[operandOffset];
}
function[0] = xk;
} else {
// strictly negative power
final double inv = 1.0 / operand[operandOffset];
double xk = FastMath.pow(inv, -n);
for (int i = 0; i <= order; ++i) {
function[i] = xk;
xk *= inv;
}
}
double coefficient = n;
for (int i = 1; i <= order; ++i) {
function[i] *= coefficient;
coefficient *= n - i;
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute power of a derivative structure.
* @param x array holding the base
* @param xOffset offset of the base in its array
* @param y array holding the exponent
* @param yOffset offset of the exponent in its array
* @param result array where result must be stored (for
* power the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void pow(final double[] x, final int xOffset,
final double[] y, final int yOffset,
final double[] result, final int resultOffset) {
final double[] logX = new double[getSize()];
log(x, xOffset, logX, 0);
final double[] yLogX = new double[getSize()];
multiply(logX, 0, y, yOffset, yLogX, 0);
exp(yLogX, 0, result, resultOffset);
}
/** Compute n<sup>th</sup> root of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param n order of the root
* @param result array where result must be stored (for
* n<sup>th</sup> root the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> array
*/
public void rootN(final double[] operand, final int operandOffset, final int n,
final double[] result, final int resultOffset) {
// create the function value and derivatives
// [x^(1/n), (1/n)x^((1/n)-1), (1-n)/n^2x^((1/n)-2), ... ]
double[] function = new double[1 + order];
double xk;
if (n == 2) {
function[0] = FastMath.sqrt(operand[operandOffset]);
xk = 0.5 / function[0];
} else if (n == 3) {
function[0] = FastMath.cbrt(operand[operandOffset]);
xk = 1.0 / (3.0 * function[0] * function[0]);
} else {
function[0] = FastMath.pow(operand[operandOffset], 1.0 / n);
xk = 1.0 / (n * FastMath.pow(function[0], n - 1));
}
final double nReciprocal = 1.0 / n;
final double xReciprocal = 1.0 / operand[operandOffset];
for (int i = 1; i <= order; ++i) {
function[i] = xk;
xk *= xReciprocal * (nReciprocal - i);
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute exponential of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* exponential the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void exp(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
Arrays.fill(function, FastMath.exp(operand[operandOffset]));
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute exp(x) - 1 of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* exponential the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void expm1(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
function[0] = FastMath.expm1(operand[operandOffset]);
Arrays.fill(function, 1, 1 + order, FastMath.exp(operand[operandOffset]));
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute natural logarithm of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* logarithm the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void log(final double[] operand, final int operandOffset,
final double[] result, final
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
function[0] = FastMath.log(operand[operandOffset]);
if (order > 0) {
double inv = 1.0 / operand[operandOffset];
double xk = inv;
for (int i = 1; i <= order; ++i) {
function[i] = xk;
xk *= -i * inv;
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Computes shifted logarithm of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* shifted logarithm the result array <em>cannot</em> be the input array)
* @param resultOffset offset of the result in its array
*/
public void log1p(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
function[0] = FastMath.log1p(operand[operandOffset]);
if (order > 0) {
double inv = 1.0 / (1.0 + operand[operandOffset]);
double xk = inv;
for (int i = 1; i <= order; ++i) {
function[i] = xk;
xk *= -i * inv;
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Computes base 10 logarithm of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* base 10 logarithm the result array <em>cannot</em> be the input array)
* @param resultOffset offset of the result in its array
*/
public void log10(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
function[0] = FastMath.log10(operand[operandOffset]);
if (order > 0) {
double inv = 1.0 / operand[operandOffset];
double xk = inv / FastMath.log(10.0);
for (int i = 1; i <= order; ++i) {
function[i] = xk;
xk *= -i * inv;
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute cosine of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* cosine the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void cos(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
function[0] = FastMath.cos(operand[operandOffset]);
if (order > 0) {
function[1] = -FastMath.sin(operand[operandOffset]);
for (int i = 2; i <= order; ++i)
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> {
function[i] = -function[i - 2];
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute sine of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* sine the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void sin(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
function[0] = FastMath.sin(operand[operandOffset]);
if (order > 0) {
function[1] = FastMath.cos(operand[operandOffset]);
for (int i = 2; i <= order; ++i) {
function[i] = -function[i - 2];
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute tangent of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* tangent the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void tan(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
final double[] function = new double[1 + order];
final double t = FastMath.tan(operand[operandOffset]);
function[0] = t;
if (order > 0) {
// the nth order derivative of tan has the form:
// dn(tan(x)/dxn = P_n(tan(x))
// where P_n(t) is a degree n+1 polynomial with same parity as n+1
// P_0(t) = t, P_1(t) = 1 + t^2, P_2(t) = 2 t (1 + t^2) ...
// the general recurrence relation for P_n is:
// P_n(x) = (1+t^2) P_(n-1)'(t)
// as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array
final double[] p = new double[order + 2];
p[1] = 1;
final double t2 = t * t;
for (int n = 1; n <= order; ++n) {
// update and evaluate polynomial P_n(t)
double v = 0;
p[n + 1] = n * p[n];
for (int k = n + 1; k >= 0; k -= 2) {
v = v * t2 + p[k];
if (k > 2) {
p[k - 2] = (k - 1) * p[k - 1] + (k - 3) * p[k - 3];
} else if (k == 2) {
p[0] = p[1];
}
}
if ((n & 0x1) == 0) {
v *= t;
}
function[n] = v;
}
}
// apply function composition
compose(operand, operandOffset
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>, function, result, resultOffset);
}
/** Compute arc cosine of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* arc cosine the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void acos(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
final double x = operand[operandOffset];
function[0] = FastMath.acos(x);
if (order > 0) {
// the nth order derivative of acos has the form:
// dn(acos(x)/dxn = P_n(x) / [1 - x^2]^((2n-1)/2)
// where P_n(x) is a degree n-1 polynomial with same parity as n-1
// P_1(x) = -1, P_2(x) = -x, P_3(x) = -2x^2 - 1 ...
// the general recurrence relation for P_n is:
// P_n(x) = (1-x^2) P_(n-1)'(x) + (2n-3) x P_(n-1)(x)
// as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array
final double[] p = new double[order];
p[0] = -1;
final double x2 = x * x;
final double f = 1.0 / (1 - x2);
double coeff = FastMath.sqrt(f);
function[1] = coeff * p[0];
for (int n = 2; n <= order; ++n) {
// update and evaluate polynomial P_n(x)
double v = 0;
p[n - 1] = (n - 1) * p[n - 2];
for (int k = n - 1; k >= 0; k -= 2) {
v = v * x2 + p[k];
if (k > 2) {
p[k - 2] = (k - 1) * p[k - 1] + (2 * n - k) * p[k - 3];
} else if (k == 2) {
p[0] = p[1];
}
}
if ((n & 0x1) == 0) {
v *= x;
}
coeff *= f;
function[n] = coeff * v;
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute arc sine of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* arc sine the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void asin(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
final double x = operand[operandOffset];
function[0] = FastMath.asin(x);
if (order > 0) {
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
// the nth order derivative of asin has the form:
// dn(asin(x)/dxn = P_n(x) / [1 - x^2]^((2n-1)/2)
// where P_n(x) is a degree n-1 polynomial with same parity as n-1
// P_1(x) = 1, P_2(x) = x, P_3(x) = 2x^2 + 1 ...
// the general recurrence relation for P_n is:
// P_n(x) = (1-x^2) P_(n-1)'(x) + (2n-3) x P_(n-1)(x)
// as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array
final double[] p = new double[order];
p[0] = 1;
final double x2 = x * x;
final double f = 1.0 / (1 - x2);
double coeff = FastMath.sqrt(f);
function[1] = coeff * p[0];
for (int n = 2; n <= order; ++n) {
// update and evaluate polynomial P_n(x)
double v = 0;
p[n - 1] = (n - 1) * p[n - 2];
for (int k = n - 1; k >= 0; k -= 2) {
v = v * x2 + p[k];
if (k > 2) {
p[k - 2] = (k - 1) * p[k - 1] + (2 * n - k) * p[k - 3];
} else if (k == 2) {
p[0] = p[1];
}
}
if ((n & 0x1) == 0) {
v *= x;
}
coeff *= f;
function[n] = coeff * v;
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute arc tangent of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* arc tangent the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void atan(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
final double x = operand[operandOffset];
function[0] = FastMath.atan(x);
if (order > 0) {
// the nth order derivative of atan has the form:
// dn(atan(x)/dxn = Q_n(x) / (1 + x^2)^n
// where Q_n(x) is a degree n-1 polynomial with same parity as n-1
// Q_1(x) = 1, Q_2(x) = -2x, Q_3(x) = 6x^2 - 2 ...
// the general recurrence relation for Q_n is:
// Q_n(x) = (1+x^2) Q_(n-1)'(x) - 2(n-1) x Q_(n-1)(x)
// as per polynomial parity, we can store coefficients of both Q_(n-1) and Q_
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>, yOffset, tmp2, 0, tmp1, 0); // y /(r - x)
atan(tmp1, 0, tmp2, 0); // atan(y / (r - x))
result[resultOffset] =
((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; // +/-pi - 2 * atan(y / (r - x))
for (int i = 1; i < tmp2.length; ++i) {
result[resultOffset + i] = -2 * tmp2[i]; // +/-pi - 2 * atan(y / (r - x))
}
}
}
/** Compute hyperbolic cosine of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* hyperbolic cosine the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void cosh(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
function[0] = FastMath.cosh(operand[operandOffset]);
if (order > 0) {
function[1] = FastMath.sinh(operand[operandOffset]);
for (int i = 2; i <= order; ++i) {
function[i] = function[i - 2];
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute hyperbolic sine of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* hyperbolic sine the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void sinh(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
function[0] = FastMath.sinh(operand[operandOffset]);
if (order > 0) {
function[1] = FastMath.cosh(operand[operandOffset]);
for (int i = 2; i <= order; ++i) {
function[i] = function[i - 2];
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute hyperbolic tangent of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* hyperbolic tangent the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void tanh(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
final double[] function = new double[1 + order];
final double t = FastMath.tanh(operand[operandOffset]);
function[0] = t;
if (order > 0) {
// the nth order derivative of tanh has the form:
// dn(tanh(x)/dxn
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> = P_n(tanh(x))
// where P_n(t) is a degree n+1 polynomial with same parity as n+1
// P_0(t) = t, P_1(t) = 1 - t^2, P_2(t) = -2 t (1 - t^2) ...
// the general recurrence relation for P_n is:
// P_n(x) = (1-t^2) P_(n-1)'(t)
// as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array
final double[] p = new double[order + 2];
p[1] = 1;
final double t2 = t * t;
for (int n = 1; n <= order; ++n) {
// update and evaluate polynomial P_n(t)
double v = 0;
p[n + 1] = -n * p[n];
for (int k = n + 1; k >= 0; k -= 2) {
v = v * t2 + p[k];
if (k > 2) {
p[k - 2] = (k - 1) * p[k - 1] - (k - 3) * p[k - 3];
} else if (k == 2) {
p[0] = p[1];
}
}
if ((n & 0x1) == 0) {
v *= t;
}
function[n] = v;
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute inverse hyperbolic cosine of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* inverse hyperbolic cosine the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void acosh(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
final double x = operand[operandOffset];
function[0] = FastMath.acosh(x);
if (order > 0) {
// the nth order derivative of acosh has the form:
// dn(acosh(x)/dxn = P_n(x) / [x^2 - 1]^((2n-1)/2)
// where P_n(x) is a degree n-1 polynomial with same parity as n-1
// P_1(x) = 1, P_2(x) = -x, P_3(x) = 2x^2 + 1 ...
// the general recurrence relation for P_n is:
// P_n(x) = (x^2-1) P_(n-1)'(x) - (2n-3) x P_(n-1)(x)
// as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array
final double[] p = new double[order];
p[0] = 1;
final double x2 = x * x;
final double f = 1.0 / (x2 - 1);
double coeff = FastMath.sqrt(f);
function[1] = coeff * p[0];
for (
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>int n = 2; n <= order; ++n) {
// update and evaluate polynomial P_n(x)
double v = 0;
p[n - 1] = (1 - n) * p[n - 2];
for (int k = n - 1; k >= 0; k -= 2) {
v = v * x2 + p[k];
if (k > 2) {
p[k - 2] = (1 - k) * p[k - 1] + (k - 2 * n) * p[k - 3];
} else if (k == 2) {
p[0] = -p[1];
}
}
if ((n & 0x1) == 0) {
v *= x;
}
coeff *= f;
function[n] = coeff * v;
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute inverse hyperbolic sine of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* inverse hyperbolic sine the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void asinh(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
final double x = operand[operandOffset];
function[0] = FastMath.asinh(x);
if (order > 0) {
// the nth order derivative of asinh has the form:
// dn(asinh(x)/dxn = P_n(x) / [x^2 + 1]^((2n-1)/2)
// where P_n(x) is a degree n-1 polynomial with same parity as n-1
// P_1(x) = 1, P_2(x) = -x, P_3(x) = 2x^2 - 1 ...
// the general recurrence relation for P_n is:
// P_n(x) = (x^2+1) P_(n-1)'(x) - (2n-3) x P_(n-1)(x)
// as per polynomial parity, we can store coefficients of both P_(n-1) and P_n in the same array
final double[] p = new double[order];
p[0] = 1;
final double x2 = x * x;
final double f = 1.0 / (1 + x2);
double coeff = FastMath.sqrt(f);
function[1] = coeff * p[0];
for (int n = 2; n <= order; ++n) {
// update and evaluate polynomial P_n(x)
double v = 0;
p[n - 1] = (1 - n) * p[n - 2];
for (int k = n - 1; k >= 0; k -= 2) {
v = v * x2 + p[k];
if (k > 2) {
p[k - 2] = (k - 1) * p[k - 1] + (k - 2 * n) * p[k - 3];
} else if (k == 2) {
p[0] = p[1];
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> if ((n & 0x1) == 0) {
v *= x;
}
coeff *= f;
function[n] = coeff * v;
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute inverse hyperbolic tangent of a derivative structure.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param result array where result must be stored (for
* inverse hyperbolic tangent the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void atanh(final double[] operand, final int operandOffset,
final double[] result, final int resultOffset) {
// create the function value and derivatives
double[] function = new double[1 + order];
final double x = operand[operandOffset];
function[0] = FastMath.atanh(x);
if (order > 0) {
// the nth order derivative of atanh has the form:
// dn(atanh(x)/dxn = Q_n(x) / (1 - x^2)^n
// where Q_n(x) is a degree n-1 polynomial with same parity as n-1
// Q_1(x) = 1, Q_2(x) = 2x, Q_3(x) = 6x^2 + 2 ...
// the general recurrence relation for Q_n is:
// Q_n(x) = (1-x^2) Q_(n-1)'(x) + 2(n-1) x Q_(n-1)(x)
// as per polynomial parity, we can store coefficients of both Q_(n-1) and Q_n in the same array
final double[] q = new double[order];
q[0] = 1;
final double x2 = x * x;
final double f = 1.0 / (1 - x2);
double coeff = f;
function[1] = coeff * q[0];
for (int n = 2; n <= order; ++n) {
// update and evaluate polynomial Q_n(x)
double v = 0;
q[n - 1] = n * q[n - 2];
for (int k = n - 1; k >= 0; k -= 2) {
v = v * x2 + q[k];
if (k > 2) {
q[k - 2] = (k - 1) * q[k - 1] + (2 * n - k + 1) * q[k - 3];
} else if (k == 2) {
q[0] = q[1];
}
}
if ((n & 0x1) == 0) {
v *= x;
}
coeff *= f;
function[n] = coeff * v;
}
}
// apply function composition
compose(operand, operandOffset, function, result, resultOffset);
}
/** Compute composition of a derivative structure by a function.
* @param operand array holding the operand
* @param operandOffset offset of the operand in its array
* @param f array of value and derivatives of the function at
* the current point (i.e. at {@code operand[operandOffset]}).
* @param result array where result must be stored (for
* composition the result array <em>cannot</em> be the input
* array)
* @param resultOffset offset of the result in its array
*/
public void
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> compose(final double[] operand, final int operandOffset, final double[] f,
final double[] result, final int resultOffset) {
for (int i = 0; i < compIndirection.length; ++i) {
final int[][] mappingI = compIndirection[i];
double r = 0;
for (int j = 0; j < mappingI.length; ++j) {
final int[] mappingIJ = mappingI[j];
double product = mappingIJ[0] * f[mappingIJ[1]];
for (int k = 2; k < mappingIJ.length; ++k) {
product *= operand[operandOffset + mappingIJ[k]];
}
r += product;
}
result[resultOffset + i] = r;
}
}
/** Evaluate Taylor expansion of a derivative structure.
* @param ds array holding the derivative structure
* @param dsOffset offset of the derivative structure in its array
* @param delta parameters offsets (Δx, Δy, ...)
* @return value of the Taylor expansion at x + Δx, y + Δy, ...
*/
public double taylor(final double[] ds, final int dsOffset, final double ... delta) {
double value = 0;
for (int i = getSize() - 1; i >= 0; --i) {
final int[] orders = getPartialDerivativeOrders(i);
double term = ds[dsOffset + i];
for (int k = 0; k < orders.length; ++k) {
if (orders[k] > 0) {
term *= FastMath.pow(delta[k], orders[k]) / ArithmeticUtils.factorial(orders[k]);
}
}
value += term;
}
return value;
}
/** Check rules set compatibility.
* @param compiler other compiler to check against instance
* @exception DimensionMismatchException if number of free parameters or orders are inconsistent
*/
public void checkCompatibility(final DSCompiler compiler)
throws DimensionMismatchException {
if (parameters != compiler.parameters) {
throw new DimensionMismatchException(parameters, compiler.parameters);
}
if (order != compiler.order) {
throw new DimensionMismatchException(order, compiler.order);
}
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>.data[i] /= a;
}
return ds;
}
/** '÷s;' operator.
* @param a right hand side parameter of the operator
* @return this÷s;a
* @exception DimensionMismatchException if number of free parameters or orders are inconsistent
*/
public DerivativeStructure divide(final DerivativeStructure a)
throws DimensionMismatchException {
compiler.checkCompatibility(a.compiler);
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.divide(data, 0, a.data, 0, result.data, 0);
return result;
}
/** '%' operator.
* @param a right hand side parameter of the operator
* @return this%a
*/
public DerivativeStructure remainder(final double a) {
final DerivativeStructure ds = new DerivativeStructure(this);
ds.data[0] = ds.data[0] % a;
return ds;
}
/** '%' operator.
* @param a right hand side parameter of the operator
* @return this%a
* @exception DimensionMismatchException if number of free parameters or orders are inconsistent
*/
public DerivativeStructure remainder(final DerivativeStructure a)
throws DimensionMismatchException {
compiler.checkCompatibility(a.compiler);
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.remainder(data, 0, a.data, 0, result.data, 0);
return result;
}
/** unary '-' operator.
* @return -this
*/
public DerivativeStructure negate() {
final DerivativeStructure ds = new DerivativeStructure(compiler);
for (int i = 0; i < ds.data.length; ++i) {
ds.data[i] = -data[i];
}
return ds;
}
/** absolute value.
* @return abs(this)
*/
public DerivativeStructure abs() {
if (Double.doubleToLongBits(data[0]) < 0) {
// we use the bits representation to also handle -0.0
return negate();
} else {
return this;
}
}
/** Get the smallest whole number larger than instance.
* @return ceil(this)
*/
public DerivativeStructure ceil() {
return new DerivativeStructure(compiler.getFreeParameters(),
compiler.getOrder(),
FastMath.ceil(data[0]));
}
/** Get the largest whole number smaller than instance.
* @return floor(this)
*/
public DerivativeStructure floor() {
return new DerivativeStructure(compiler.getFreeParameters(),
compiler.getOrder(),
FastMath.floor(data[0]));
}
/** Get the whole number that is the nearest to the instance, or the even one if x is exactly half way between two integers.
* @return a double number r such that r is an integer r - 0.5 <= this <= r + 0.5
*/
public DerivativeStructure rint() {
return new DerivativeStructure(compiler.getFreeParameters(),
compiler.getOrder(),
FastMath.rint(data[0]));
}
/** Get the closest long to instance value.
* @return closest long to {@link #getValue()}
*/
public long round() {
return FastMath.round(data[0]);
}
/** Compute the signum of the instance.
* The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
* @return -1.0, -0.0, +0.0, +1.0 or NaN depending on sign of a
*/
public
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> DerivativeStructure signum() {
return new DerivativeStructure(compiler.getFreeParameters(),
compiler.getOrder(),
FastMath.signum(data[0]));
}
/**
* Returns the instance with the sign of the argument.
* A NaN {@code sign} argument is treated as positive.
*
* @param sign the sign for the returned value
* @return the instance with the same sign as the {@code sign} argument
*/
public DerivativeStructure copySign(final double sign){
long m = Double.doubleToLongBits(data[0]);
long s = Double.doubleToLongBits(sign);
if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK
return this;
}
return negate(); // flip sign
}
/**
* Return the exponent of the instance value, removing the bias.
* <p>
* For double numbers of the form 2<sup>x</sup>, the unbiased
* exponent is exactly x.
* </p>
* @return exponent for instance in IEEE754 representation, without bias
*/
public int getExponent() {
return FastMath.getExponent(data[0]);
}
/**
* Multiply the instance by a power of 2.
* @param n power of 2
* @return this × 2<sup>n</sup>
*/
public DerivativeStructure scalb(final int n) {
final DerivativeStructure ds = new DerivativeStructure(compiler);
for (int i = 0; i < ds.data.length; ++i) {
ds.data[i] = FastMath.scalb(data[i], n);
}
return ds;
}
/**
* Returns the hypotenuse of a triangle with sides {@code x} and {@code y}
* - sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)<br/>
* avoiding intermediate overflow or underflow.
*
* <ul>
* <li> If either argument is infinite, then the result is positive infinity.</li>
* <li> else, if either argument is NaN then the result is NaN.</li>
* </ul>
*
* @param x a value
* @param y a value
* @return sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)
* @exception DimensionMismatchException if number of free parameters or orders are inconsistent
*/
public static DerivativeStructure hypot(final DerivativeStructure x, final DerivativeStructure y)
throws DimensionMismatchException {
x.compiler.checkCompatibility(y.compiler);
if (Double.isInfinite(x.data[0]) || Double.isInfinite(y.data[0])) {
return new DerivativeStructure(x.compiler.getFreeParameters(),
x.compiler.getFreeParameters(),
Double.POSITIVE_INFINITY);
} else if (Double.isNaN(x.data[0]) || Double.isNaN(y.data[0])) {
return new DerivativeStructure(x.compiler.getFreeParameters(),
x.compiler.getFreeParameters(),
Double.NaN);
} else {
final int expX = x.getExponent();
final int expY = y.getExponent();
if (expX > expY + 27) {
// y is neglectible with respect to x
return x.abs();
} else if (expY > expX + 27) {
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> // x is neglectible with respect to y
return y.abs();
} else {
// find an intermediate scale to avoid both overflow and underflow
final int middleExp = (expX + expY) / 2;
// scale parameters without losing precision
final DerivativeStructure scaledX = x.scalb(-middleExp);
final DerivativeStructure scaledY = y.scalb(-middleExp);
// compute scaled hypotenuse
final DerivativeStructure scaledH =
scaledX.multiply(scaledX).add(scaledY.multiply(scaledY)).sqrt();
// remove scaling
return scaledH.scalb(middleExp);
}
}
}
/** Compute composition of the instance by a univariate function.
* @param f array of value and derivatives of the function at
* the current point (i.e. [f({@link #getValue()}),
* f'({@link #getValue()}), f''({@link #getValue()})...]).
* @return f(this)
* @exception DimensionMismatchException if the number of derivatives
* in the array is not equal to {@link #getOrder() order} + 1
*/
public DerivativeStructure compose(final double ... f) {
if (f.length != getOrder() + 1) {
throw new DimensionMismatchException(f.length, getOrder() + 1);
}
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.compose(data, 0, f, result.data, 0);
return result;
}
/** {@inheritDoc} */
public DerivativeStructure reciprocal() {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.pow(data, 0, -1, result.data, 0);
return result;
}
/** Square root.
* @return square root of the instance
*/
public DerivativeStructure sqrt() {
return rootN(2);
}
/** Cubic root.
* @return cubic root of the instance
*/
public DerivativeStructure cbrt() {
return rootN(3);
}
/** N<sup>th</sup> root.
* @param n order of the root
* @return n<sup>th</sup> root of the instance
*/
public DerivativeStructure rootN(final int n) {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.rootN(data, 0, n, result.data, 0);
return result;
}
/** {@inheritDoc} */
public Field<DerivativeStructure> getField() {
return new Field<DerivativeStructure>() {
/** {@inheritDoc} */
public DerivativeStructure getZero() {
return new DerivativeStructure(compiler.getFreeParameters(), compiler.getOrder(), 0.0);
}
/** {@inheritDoc} */
public DerivativeStructure getOne() {
return new DerivativeStructure(compiler.getFreeParameters(), compiler.getOrder(), 1.0);
}
/** {@inheritDoc} */
public Class<? extends FieldElement<DerivativeStructure>> getRuntimeClass() {
return DerivativeStructure.class;
}
};
}
/** Power operation.
* @param p power to apply
* @return this<sup>p</sup>
*/
public DerivativeStructure pow(final double p) {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.pow(data, 0, p, result.data, 0);
return result;
}
/** Integer power operation.
* @param n power to apply
* @return this
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>() {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.asin(data, 0, result.data, 0);
return result;
}
/** Arc tangent operation.
* @return atan(this)
*/
public DerivativeStructure atan() {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.atan(data, 0, result.data, 0);
return result;
}
/** Two arguments arc tangent operation.
* @param y first argument of the arc tangent
* @param x second argument of the arc tangent
* @return atan2(y, x)
* @exception DimensionMismatchException if number of free parameters or orders are inconsistent
*/
public static DerivativeStructure atan2(final DerivativeStructure y, final DerivativeStructure x)
throws DimensionMismatchException {
y.compiler.checkCompatibility(x.compiler);
final DerivativeStructure result = new DerivativeStructure(y.compiler);
y.compiler.atan2(y.data, 0, x.data, 0, result.data, 0);
return result;
}
/** Hyperbolic cosine operation.
* @return cosh(this)
*/
public DerivativeStructure cosh() {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.cosh(data, 0, result.data, 0);
return result;
}
/** Hyperbolic sine operation.
* @return sinh(this)
*/
public DerivativeStructure sinh() {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.sinh(data, 0, result.data, 0);
return result;
}
/** Hyperbolic tangent operation.
* @return tanh(this)
*/
public DerivativeStructure tanh() {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.tanh(data, 0, result.data, 0);
return result;
}
/** Inverse hyperbolic cosine operation.
* @return acosh(this)
*/
public DerivativeStructure acosh() {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.acosh(data, 0, result.data, 0);
return result;
}
/** Inverse hyperbolic sine operation.
* @return asin(this)
*/
public DerivativeStructure asinh() {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.asinh(data, 0, result.data, 0);
return result;
}
/** Inverse hyperbolic tangent operation.
* @return atanh(this)
*/
public DerivativeStructure atanh() {
final DerivativeStructure result = new DerivativeStructure(compiler);
compiler.atanh(data, 0, result.data, 0);
return result;
}
/** Convert radians to degrees, with error of less than 0.5 ULP
* @return instance converted into degrees
*/
public DerivativeStructure toDegrees() {
final DerivativeStructure ds = new DerivativeStructure(compiler);
for (int i = 0; i < ds.data.length; ++i) {
ds.data[i] = FastMath.toDegrees(data[i]);
}
return ds;
}
/** Convert degrees to radians, with error of less than 0.5 ULP
* @return instance converted into radians
*/
public DerivativeStructure toRadians
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>() {
final DerivativeStructure ds = new DerivativeStructure(compiler);
for (int i = 0; i < ds.data.length; ++i) {
ds.data[i] = FastMath.toRadians(data[i]);
}
return ds;
}
/** Evaluate Taylor expansion a derivative structure.
* @param delta parameters offsets (Δx, Δy, ...)
* @return value of the Taylor expansion at x + Δx, y + Δy, ...
*/
public double taylor(final double ... delta) {
return compiler.taylor(data, 0, delta);
}
/**
* Replace the instance with a data transfer object for serialization.
* @return data transfer object that will be serialized
*/
private Object writeReplace() {
return new DataTransferObject(compiler.getFreeParameters(), compiler.getOrder(), data);
}
/** Internal class used only for serialization. */
private static class DataTransferObject implements Serializable {
/** Serializable UID. */
private static final long serialVersionUID = 20120730L;
/** Number of variables.
* @serial
*/
private final int variables;
/** Derivation order.
* @serial
*/
private final int order;
/** Partial derivatives.
* @serial
*/
private final double[] data;
/** Simple constructor.
* @param variables number of variables
* @param order derivation order
* @param data partial derivatives
*/
public DataTransferObject(final int variables, final int order, final double[] data) {
this.variables = variables;
this.order = order;
this.data = data;
}
/** Replace the deserialized data transfer object with a {@link DerivativeStructure}.
* @return replacement {@link DerivativeStructure}
*/
private Object readResolve() {
return new DerivativeStructure(variables, order, data);
}
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>itter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer());
for (int i = 0; i <= degree; ++i) {
fitter.addObservedPoint(1.0, i, p.value(i));
}
final double[] init = new double[degree + 1];
PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init));
for (double x = -1.0; x < 1.0; x += 0.01) {
double error = FastMath.abs(p.value(x) - fitted.value(x)) /
(1.0 + FastMath.abs(p.value(x)));
Assert.assertEquals(0.0, error, 1.0e-6);
}
}
}
@Test
public void testSmallError() {
Random randomizer = new Random(53882150042l);
double maxError = 0;
for (int degree = 0; degree < 10; ++degree) {
PolynomialFunction p = buildRandomPolynomial(degree, randomizer);
PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer());
for (double x = -1.0; x < 1.0; x += 0.01) {
fitter.addObservedPoint(1.0, x,
p.value(x) + 0.1 * randomizer.nextGaussian());
}
final double[] init = new double[degree + 1];
PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init));
for (double x = -1.0; x < 1.0; x += 0.01) {
double error = FastMath.abs(p.value(x) - fitted.value(x)) /
(1.0 + FastMath.abs(p.value(x)));
maxError = FastMath.max(maxError, error);
Assert.assertTrue(FastMath.abs(error) < 0.1);
}
}
Assert.assertTrue(maxError > 0.01);
}
@Test
public void testMath798() {
final double tol = 1e-14;
final SimpleVectorValueChecker checker = new SimpleVectorValueChecker(tol, tol);
final double[] init = new double[] { 0, 0 };
final int maxEval = 3;
final double[] lm = doMath798(new LevenbergMarquardtOptimizer(checker), maxEval, init);
final double[] gn = doMath798(new GaussNewtonOptimizer(checker), maxEval, init);
for (int i = 0; i <= 1; i++) {
Assert.assertEquals(lm[i], gn[i], tol);
}
}
/**
* This test shows that the user can set the maximum number of iterations
* to avoid running for too long.
* But in the test case, the real problem is that the tolerance is way too
* stringent.
*/
@Test(expected=TooManyEvaluationsException.class)
public void testMath798WithToleranceTooLow() {
final double tol = 1e-100;
final SimpleVectorValueChecker checker = new SimpleVectorValueChecker(tol, tol);
final double[] init = new double[] { 0, 0 };
final int maxEval = 10000; // Trying hard to fit.
final double[] gn = doMath798(new GaussNewtonOptimizer(checker
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> 3.14248E-13);
fitter.addObservedPoint(-0.183, 3.1172E-13);
fitter.addObservedPoint(-0.182, 3.12912E-13);
fitter.addObservedPoint(-0.181, 3.06761E-13);
fitter.addObservedPoint(-0.18, 2.8559E-13);
fitter.addObservedPoint(-0.179, 2.86806E-13);
fitter.addObservedPoint(-0.178, 2.985E-13);
fitter.addObservedPoint(-0.177, 2.67148E-13);
fitter.addObservedPoint(-0.176, 2.94173E-13);
fitter.addObservedPoint(-0.175, 3.27528E-13);
fitter.addObservedPoint(-0.174, 3.33858E-13);
fitter.addObservedPoint(-0.173, 2.97511E-13);
fitter.addObservedPoint(-0.172, 2.8615E-13);
fitter.addObservedPoint(-0.171, 2.84624E-13);
final double[] coeff = fitter.fit(maxEval,
new PolynomialFunction.Parametric(),
init);
return coeff;
}
@Test
public void testRedundantSolvable() {
// Levenberg-Marquardt should handle redundant information gracefully
checkUnsolvableProblem(new LevenbergMarquardtOptimizer(), true);
}
@Test
public void testRedundantUnsolvable() {
// Gauss-Newton should not be able to solve redundant information
checkUnsolvableProblem(new GaussNewtonOptimizer(true, new SimpleVectorValueChecker(1e-15, 1e-15)), false);
}
@Test
public void testLargeSample() {
Random randomizer = new Random(0x5551480dca5b369bl);
double maxError = 0;
for (int degree = 0; degree < 10; ++degree) {
PolynomialFunction p = buildRandomPolynomial(degree, randomizer);
PolynomialFitter fitter = new PolynomialFitter(new LevenbergMarquardtOptimizer());
for (int i = 0; i < 40000; ++i) {
double x = -1.0 + i / 20000.0;
fitter.addObservedPoint(1.0, x,
p.value(x) + 0.1 * randomizer.nextGaussian());
}
final double[] init = new double[degree + 1];
PolynomialFunction fitted = new PolynomialFunction(fitter.fit(init));
for (double x = -1.0; x < 1.0; x += 0.01) {
double error = FastMath.abs(p.value(x) - fitted.value(x)) /
(1.0 + FastMath.abs(p.value(x)));
maxError = FastMath.max(maxError, error);
Assert.assertTrue(FastMath.
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.linear;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.commons.math3.exception.MathUnsupportedOperationException;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.NotPositiveException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.exception.MathArithmeticException;
import org.apache.commons.math3.analysis.FunctionUtils;
import org.apache.commons.math3.analysis.function.Add;
import org.apache.commons.math3.analysis.function.Multiply;
import org.apache.commons.math3.analysis.function.Divide;
import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.util.FastMath;
/**
* Class defining a real-valued vector with basic algebraic operations.
* <p>
* vector element indexing is 0-based -- e.g., {@code getEntry(0)}
* returns the first element of the vector.
* </p>
* <p>
* The {@code code map} and {@code mapToSelf} methods operate
* on vectors element-wise, i.e. they perform the same operation (adding a scalar,
* applying a function ...) on each element in turn. The {@code map}
* versions create a new vector to hold the result and do not change the instance.
* The {@code mapToSelf} version uses the instance itself to store the
* results, so the instance is changed by this method. In all cases, the result
* vector is returned by the methods, allowing the <i>fluent API</i>
* style, like this:
* </p>
* <pre>
* RealVector result = v.mapAddToSelf(3.4).mapToSelf(new Tan()).mapToSelf(new Power(2.3));
* </pre>
*
* @version $Id$
* @since 2.1
*/
public abstract class RealVector {
/**
* Returns the size of the vector.
*
* @return the size of this vector.
*/
public abstract int getDimension();
/**
* Return the entry at the specified index.
*
* @param index Index location of entry to be fetched.
* @return the vector entry at {@code index}.
* @throws OutOfRangeException if the index is not valid.
* @see #setEntry(int, double)
*/
public abstract double getEntry(int index) throws OutOfRangeException;
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> /**
* Set a single element.
*
* @param index element index.
* @param value new value for the element.
* @throws OutOfRangeException if the index is not valid.
* @see #getEntry(int)
*/
public abstract void setEntry(int index, double value)
throws OutOfRangeException;
/**
* Change an entry at the specified index.
*
* @param index Index location of entry to be set.
* @param increment Value to add to the vector entry.
* @throws OutOfRangeException if the index is not valid.
* @since 3.0
*/
public void addToEntry(int index, double increment)
throws OutOfRangeException {
setEntry(index, getEntry(index) + increment);
}
/**
* Construct a new vector by appending a vector to this vector.
*
* @param v vector to append to this one.
* @return a new vector.
*/
public abstract RealVector append(RealVector v);
/**
* Construct a new vector by appending a double to this vector.
*
* @param d double to append.
* @return a new vector.
*/
public abstract RealVector append(double d);
/**
* Get a subvector from consecutive elements.
*
* @param index index of first element.
* @param n number of elements to be retrieved.
* @return a vector containing n elements.
* @throws OutOfRangeException if the index is not valid.
* @throws NotPositiveException if the number of elements is not positive.
*/
public abstract RealVector getSubVector(int index, int n)
throws NotPositiveException, OutOfRangeException;
/**
* Set a sequence of consecutive elements.
*
* @param index index of first element to be set.
* @param v vector containing the values to set.
* @throws OutOfRangeException if the index is not valid.
*/
public abstract void setSubVector(int index, RealVector v)
throws OutOfRangeException;
/**
* Check whether any coordinate of this vector is {@code NaN}.
*
* @return {@code true} if any coordinate of this vector is {@code NaN},
* {@code false} otherwise.
*/
public abstract boolean isNaN();
/**
* Check whether any coordinate of this vector is infinite and none are {@code NaN}.
*
* @return {@code true} if any coordinate of this vector is infinite and
* none are {@code NaN}, {@code false} otherwise.
*/
public abstract boolean isInfinite();
/**
* Check if instance and specified vectors have the same dimension.
*
* @param v Vector to compare instance with.
* @throws DimensionMismatchException if the vectors do not
* have the same dimension.
*/
protected void checkVectorDimensions(RealVector v)
throws DimensionMismatchException {
checkVectorDimensions(v.getDimension());
}
/**
* Check if instance dimension is equal to some expected value.
*
* @param n Expected dimension.
* @throws DimensionMismatchException if the dimension is
* inconsistent with the vector size.
*/
protected void checkVectorDimensions(int n)
throws DimensionMismatchException {
int d = getDimension();
if (d != n) {
throw new DimensionMismatchException(d, n);
}
}
/**
* Check if an index is valid.
*
* @param index Index to check.
* @exception OutOfRangeException if {@code index} is not valid.
*/
protected void checkIndex(final int index) throws OutOfRangeException {
if (index < 0 ||
index >= getDimension()) {
throw new OutOfRangeException(Localized
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Formats.INDEX,
index, 0, getDimension() - 1);
}
}
/**
* Checks that the indices of a subvector are valid.
*
* @param start the index of the first entry of the subvector
* @param end the index of the last entry of the subvector (inclusive)
* @throws OutOfRangeException if {@code start} of {@code end} are not valid
* @throws NumberIsTooSmallException if {@code end < start}
* @since 3.1
*/
protected void checkIndices(final int start, final int end)
throws NumberIsTooSmallException, OutOfRangeException {
final int dim = getDimension();
if ((start < 0) || (start >= dim)) {
throw new OutOfRangeException(LocalizedFormats.INDEX, start, 0,
dim - 1);
}
if ((end < 0) || (end >= dim)) {
throw new OutOfRangeException(LocalizedFormats.INDEX, end, 0,
dim - 1);
}
if (end < start) {
// TODO Use more specific error message
throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW,
end, start, false);
}
}
/**
* Compute the sum of this vector and {@code v}.
* Returns a new vector. Does not change instance data.
*
* @param v Vector to be added.
* @return {@code this} + {@code v}.
* @throws DimensionMismatchException if {@code v} is not the same size as
* {@code this} vector.
*/
public RealVector add(RealVector v) throws DimensionMismatchException {
checkVectorDimensions(v);
RealVector result = v.copy();
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
final int index = e.getIndex();
result.setEntry(index, e.getValue() + result.getEntry(index));
}
return result;
}
/**
* Subtract {@code v} from this vector.
* Returns a new vector. Does not change instance data.
*
* @param v Vector to be subtracted.
* @return {@code this} - {@code v}.
* @throws DimensionMismatchException if {@code v} is not the same size as
* {@code this} vector.
*/
public RealVector subtract(RealVector v) throws DimensionMismatchException {
checkVectorDimensions(v);
RealVector result = v.mapMultiply(-1d);
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
final int index = e.getIndex();
result.setEntry(index, e.getValue() + result.getEntry(index));
}
return result;
}
/**
* Add a value to each entry.
* Returns a new vector. Does not change instance data.
*
* @param d Value to be added to each entry.
* @return {@code this} + {@code d}.
*/
public RealVector mapAdd(double d) {
return copy().mapAddToSelf(d);
}
/**
* Add a value to each entry.
* The instance is changed in-place.
*
* @param d Value to be added to each entry.
* @return {@code this}.
*/
public RealVector mapAddToSelf(double d) {
if (d != 0) {
return mapToSelf(FunctionUtils.fix2ndArgument(new Add(), d));
}
return this;
}
/**
* Returns a (deep) copy of this vector.
*
*
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> @return a vector copy.
*/
public abstract RealVector copy();
/**
* Compute the dot product of this vector with {@code v}.
*
* @param v Vector with which dot product should be computed
* @return the scalar dot product between this instance and {@code v}.
* @throws DimensionMismatchException if {@code v} is not the same size as
* {@code this} vector.
*/
public double dotProduct(RealVector v) throws DimensionMismatchException {
checkVectorDimensions(v);
double d = 0;
final int n = getDimension();
for (int i = 0; i < n; i++) {
d += getEntry(i) * v.getEntry(i);
}
return d;
}
/**
* Computes the cosine of the angle between this vector and the
* argument.
*
* @param v Vector.
* @return the cosine of the angle between this vector and {@code v}.
* @throws MathArithmeticException if {@code this} or {@code v} is the null
* vector
* @throws DimensionMismatchException if the dimensions of {@code this} and
* {@code v} do not match
*/
public double cosine(RealVector v) throws DimensionMismatchException,
MathArithmeticException {
final double norm = getNorm();
final double vNorm = v.getNorm();
if (norm == 0 ||
vNorm == 0) {
throw new MathArithmeticException(LocalizedFormats.ZERO_NORM);
}
return dotProduct(v) / (norm * vNorm);
}
/**
* Element-by-element division.
*
* @param v Vector by which instance elements must be divided.
* @return a vector containing this[i] / v[i] for all i.
* @throws DimensionMismatchException if {@code v} is not the same size as
* {@code this} vector.
* @deprecated As of version 3.1, this method is deprecated, and will be
* removed in version 4.0. This decision follows the discussion reported in
* <a href="https://issues.apache.org/jira/browse/MATH-803?focusedCommentId=13399150#comment-13399150">MATH-803</a>.
* Uses of this method involving sparse implementations of
* {@link RealVector} might lead to wrong results. Since there is no
* satisfactory correction to this bug, this method is deprecated. Users who
* want to preserve this feature are advised to implement
* {@link RealVectorPreservingVisitor} (possibly ignoring corner cases for
* the sake of efficiency).
*/
@Deprecated
public abstract RealVector ebeDivide(RealVector v)
throws DimensionMismatchException;
/**
* Element-by-element multiplication.
*
* @param v Vector by which instance elements must be multiplied
* @return a vector containing this[i] * v[i] for all i.
* @throws DimensionMismatchException if {@code v} is not the same size as
* {@code this} vector.
* @deprecated As of version 3.1, this method is deprecated, and will be
* removed in version 4.0. This decision follows the discussion reported in
* <a href="https://issues.apache.org/jira/browse/MATH-803?focusedCommentId=13399150#comment-13399150">MATH-803</a>.
* Uses of this method involving sparse implementations of
* {@link RealVector} might lead to wrong results. Since there is no
* satisfactory correction to this bug,
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> this method is deprecated. Users who
* want to preserve this feature are advised to implement
* {@link RealVectorPreservingVisitor} (possibly ignoring corner cases for
* the sake of efficiency).
*/
@Deprecated
public abstract RealVector ebeMultiply(RealVector v)
throws DimensionMismatchException;
/**
* Distance between two vectors.
* <p>This method computes the distance consistent with the
* L<sub>2</sub> norm, i.e. the square root of the sum of
* element differences, or Euclidean distance.</p>
*
* @param v Vector to which distance is requested.
* @return the distance between two vectors.
* @throws DimensionMismatchException if {@code v} is not the same size as
* {@code this} vector.
* @see #getL1Distance(RealVector)
* @see #getLInfDistance(RealVector)
* @see #getNorm()
*/
public double getDistance(RealVector v) throws DimensionMismatchException {
checkVectorDimensions(v);
double d = 0;
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
final double diff = e.getValue() - v.getEntry(e.getIndex());
d += diff * diff;
}
return FastMath.sqrt(d);
}
/**
* Returns the L<sub>2</sub> norm of the vector.
* <p>The L<sub>2</sub> norm is the root of the sum of
* the squared elements.</p>
*
* @return the norm.
* @see #getL1Norm()
* @see #getLInfNorm()
* @see #getDistance(RealVector)
*/
public double getNorm() {
double sum = 0;
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
final double value = e.getValue();
sum += value * value;
}
return FastMath.sqrt(sum);
}
/**
* Returns the L<sub>1</sub> norm of the vector.
* <p>The L<sub>1</sub> norm is the sum of the absolute
* values of the elements.</p>
*
* @return the norm.
* @see #getNorm()
* @see #getLInfNorm()
* @see #getL1Distance(RealVector)
*/
public double getL1Norm() {
double norm = 0;
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
norm += FastMath.abs(e.getValue());
}
return norm;
}
/**
* Returns the L<sub>∞</sub> norm of the vector.
* <p>The L<sub>∞</sub> norm is the max of the absolute
* values of the elements.</p>
*
* @return the norm.
* @see #getNorm()
* @see #getL1Norm()
* @see #getLInfDistance(RealVector)
*/
public double getLInfNorm() {
double norm = 0;
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
norm = FastMath.max(norm, FastMath.abs(e.getValue()));
}
return norm;
}
/**
* Distance between two vectors.
* <p>This method computes the distance consistent with
* L<sub>1</sub> norm, i.e. the sum of the absolute values of
* the
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> elements differences.</p>
*
* @param v Vector to which distance is requested.
* @return the distance between two vectors.
* @throws DimensionMismatchException if {@code v} is not the same size as
* {@code this} vector.
*/
public double getL1Distance(RealVector v)
throws DimensionMismatchException {
checkVectorDimensions(v);
double d = 0;
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
d += FastMath.abs(e.getValue() - v.getEntry(e.getIndex()));
}
return d;
}
/**
* Distance between two vectors.
* <p>This method computes the distance consistent with
* L<sub>∞</sub> norm, i.e. the max of the absolute values of
* element differences.</p>
*
* @param v Vector to which distance is requested.
* @return the distance between two vectors.
* @throws DimensionMismatchException if {@code v} is not the same size as
* {@code this} vector.
* @see #getDistance(RealVector)
* @see #getL1Distance(RealVector)
* @see #getLInfNorm()
*/
public double getLInfDistance(RealVector v)
throws DimensionMismatchException {
checkVectorDimensions(v);
double d = 0;
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
d = FastMath.max(FastMath.abs(e.getValue() - v.getEntry(e.getIndex())), d);
}
return d;
}
/**
* Get the index of the minimum entry.
*
* @return the index of the minimum entry or -1 if vector length is 0
* or all entries are {@code NaN}.
*/
public int getMinIndex() {
int minIndex = -1;
double minValue = Double.POSITIVE_INFINITY;
Iterator<Entry> iterator = iterator();
while (iterator.hasNext()) {
final Entry entry = iterator.next();
if (entry.getValue() <= minValue) {
minIndex = entry.getIndex();
minValue = entry.getValue();
}
}
return minIndex;
}
/**
* Get the value of the minimum entry.
*
* @return the value of the minimum entry or {@code NaN} if all
* entries are {@code NaN}.
*/
public double getMinValue() {
final int minIndex = getMinIndex();
return minIndex < 0 ? Double.NaN : getEntry(minIndex);
}
/**
* Get the index of the maximum entry.
*
* @return the index of the maximum entry or -1 if vector length is 0
* or all entries are {@code NaN}
*/
public int getMaxIndex() {
int maxIndex = -1;
double maxValue = Double.NEGATIVE_INFINITY;
Iterator<Entry> iterator = iterator();
while (iterator.hasNext()) {
final Entry entry = iterator.next();
if (entry.getValue() >= maxValue) {
maxIndex = entry.getIndex();
maxValue = entry.getValue();
}
}
return maxIndex;
}
/**
* Get the value of the maximum entry.
*
* @return the value of the maximum entry or {@code NaN} if all
* entries are {@code NaN}.
*/
public double getMaxValue() {
final int maxIndex = getMaxIndex();
return maxIndex < 0 ? Double.NaN : getEntry(maxIndex);
}
/**
* Multiply each entry by the argument. Returns a new vector.
* Does not change
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> instance data.
*
* @param d Multiplication factor.
* @return {@code this} * {@code d}.
*/
public RealVector mapMultiply(double d) {
return copy().mapMultiplyToSelf(d);
}
/**
* Multiply each entry.
* The instance is changed in-place.
*
* @param d Multiplication factor.
* @return {@code this}.
*/
public RealVector mapMultiplyToSelf(double d){
return mapToSelf(FunctionUtils.fix2ndArgument(new Multiply(), d));
}
/**
* Subtract a value from each entry. Returns a new vector.
* Does not change instance data.
*
* @param d Value to be subtracted.
* @return {@code this} - {@code d}.
*/
public RealVector mapSubtract(double d) {
return copy().mapSubtractToSelf(d);
}
/**
* Subtract a value from each entry.
* The instance is changed in-place.
*
* @param d Value to be subtracted.
* @return {@code this}.
*/
public RealVector mapSubtractToSelf(double d){
return mapAddToSelf(-d);
}
/**
* Divide each entry by the argument. Returns a new vector.
* Does not change instance data.
*
* @param d Value to divide by.
* @return {@code this} / {@code d}.
*/
public RealVector mapDivide(double d) {
return copy().mapDivideToSelf(d);
}
/**
* Divide each entry by the argument.
* The instance is changed in-place.
*
* @param d Value to divide by.
* @return {@code this}.
*/
public RealVector mapDivideToSelf(double d){
return mapToSelf(FunctionUtils.fix2ndArgument(new Divide(), d));
}
/**
* Compute the outer product.
*
* @param v Vector with which outer product should be computed.
* @return the matrix outer product between this instance and {@code v}.
*/
public RealMatrix outerProduct(RealVector v) {
final int m = this.getDimension();
final int n = v.getDimension();
final RealMatrix product;
if (v instanceof SparseRealVector || this instanceof SparseRealVector) {
product = new OpenMapRealMatrix(m, n);
} else {
product = new Array2DRowRealMatrix(m, n);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
product.setEntry(i, j, this.getEntry(i) * v.getEntry(j));
}
}
return product;
}
/**
* Find the orthogonal projection of this vector onto another vector.
*
* @param v vector onto which instance must be projected.
* @return projection of the instance onto {@code v}.
* @throws DimensionMismatchException if {@code v} is not the same size as
* {@code this} vector.
* @throws MathArithmeticException if {@code this} or {@code v} is the null
* vector
*/
public RealVector projection(final RealVector v)
throws DimensionMismatchException, MathArithmeticException {
final double norm2 = v.dotProduct(v);
if (norm2 == 0.0) {
throw new MathArithmeticException(LocalizedFormats.ZERO_NORM);
}
return v.mapMultiply(dotProduct(v) / v.dotProduct(v));
}
/**
* Set all elements to a single value.
*
* @param value Single value to set for all elements.
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> */
public void set(double value) {
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
e.setValue(value);
}
}
/**
* Convert the vector to an array of {@code double}s.
* The array is independent from this vector data: the elements
* are copied.
*
* @return an array containing a copy of the vector elements.
*/
public double[] toArray() {
int dim = getDimension();
double[] values = new double[dim];
for (int i = 0; i < dim; i++) {
values[i] = getEntry(i);
}
return values;
}
/**
* Creates a unit vector pointing in the direction of this vector.
* The instance is not changed by this method.
*
* @return a unit vector pointing in direction of this vector.
* @throws MathArithmeticException if the norm is zero.
*/
public RealVector unitVector() throws MathArithmeticException {
final double norm = getNorm();
if (norm == 0) {
throw new MathArithmeticException(LocalizedFormats.ZERO_NORM);
}
return mapDivide(norm);
}
/**
* Converts this vector into a unit vector.
* The instance itself is changed by this method.
*
* @throws MathArithmeticException if the norm is zero.
*/
public void unitize() throws MathArithmeticException {
final double norm = getNorm();
if (norm == 0) {
throw new MathArithmeticException(LocalizedFormats.ZERO_NORM);
}
mapDivideToSelf(getNorm());
}
/**
* Create a sparse iterator over the vector, which may omit some entries.
* Specialized implementations may choose to not iterate over all
* dimensions, either because those values are unset, or are equal
* to defaultValue(), or are small enough to be ignored for the
* purposes of iteration. No guarantees are made about order of iteration.
* In dense implementations, this method will often delegate to
* {@link #iterator()}.
*
* <p>Note: derived classes are required to return an {@link Iterator} that
* returns non-null {@link Entry} objects as long as {@link Iterator#hasNext()}
* returns {@code true}.</p>
*
* @return a sparse iterator.
* @deprecated As of 3.1, this method is deprecated, because its interface
* is too confusing (see
* <a href="https://issues.apache.org/jira/browse/MATH-875">JIRA MATH-875</a>).
* This method will be completely removed in 4.0.
*/
@Deprecated
public Iterator<Entry> sparseIterator() {
return new SparseEntryIterator();
}
/**
* Generic dense iterator. Iteration is in increasing order
* of the vector index.
*
* <p>Note: derived classes are required to return an {@link Iterator} that
* returns non-null {@link Entry} objects as long as {@link Iterator#hasNext()}
* returns {@code true}.</p>
*
* @return a dense iterator.
*/
public Iterator<Entry> iterator() {
final int dim = getDimension();
return new Iterator<Entry>() {
/** Current index. */
private int i = 0;
/** Current entry. */
private Entry e = new Entry();
/** {@inheritDoc} */
public boolean hasNext() {
return i < dim;
}
/** {@inheritDoc} */
public Entry next() {
if (i < dim) {
e.setIndex(i++);
return e;
} else {
throw new NoSuchElementException();
}
}
/**
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
* {@inheritDoc}
*
* @throws MathUnsupportedOperationException in all circumstances.
*/
public void remove() throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
};
}
/**
* Acts as if implemented as:
* <pre>
* return copy().mapToSelf(function);
* </pre>
* Returns a new vector. Does not change instance data.
*
* @param function Function to apply to each entry.
* @return a new vector.
*/
public RealVector map(UnivariateFunction function) {
return copy().mapToSelf(function);
}
/**
* Acts as if it is implemented as:
* <pre>
* Entry e = null;
* for(Iterator<Entry> it = iterator(); it.hasNext(); e = it.next()) {
* e.setValue(function.value(e.getValue()));
* }
* </pre>
* Entries of this vector are modified in-place by this method.
*
* @param function Function to apply to each entry.
* @return a reference to this vector.
*/
public RealVector mapToSelf(UnivariateFunction function) {
Iterator<Entry> it = iterator();
while (it.hasNext()) {
final Entry e = it.next();
e.setValue(function.value(e.getValue()));
}
return this;
}
/**
* Returns a new vector representing {@code a * this + b * y}, the linear
* combination of {@code this} and {@code y}.
* Returns a new vector. Does not change instance data.
*
* @param a Coefficient of {@code this}.
* @param b Coefficient of {@code y}.
* @param y Vector with which {@code this} is linearly combined.
* @return a vector containing {@code a * this[i] + b * y[i]} for all
* {@code i}.
* @throws DimensionMismatchException if {@code y} is not the same size as
* {@code this} vector.
*/
public RealVector combine(double a, double b, RealVector y)
throws DimensionMismatchException {
return copy().combineToSelf(a, b, y);
}
/**
* Updates {@code this} with the linear combination of {@code this} and
* {@code y}.
*
* @param a Weight of {@code this}.
* @param b Weight of {@code y}.
* @param y Vector with which {@code this} is linearly combined.
* @return {@code this}, with components equal to
* {@code a * this[i] + b * y[i]} for all {@code i}.
* @throws DimensionMismatchException if {@code y} is not the same size as
* {@code this} vector.
*/
public RealVector combineToSelf(double a, double b, RealVector y)
throws DimensionMismatchException {
checkVectorDimensions(y);
for (int i = 0; i < getDimension(); i++) {
final double xi = getEntry(i);
final double yi = y.getEntry(i);
setEntry(i, a * xi + b * yi);
}
return this;
}
/**
* Visits (but does not alter) all entries of this vector in default order
* (increasing index).
*
* @param visitor the visitor to be used to process the entries of this
* vector
* @return the value returned by {@link RealVectorPreservingVisitor#end()}
* at the end of the walk
* @since 3.1
*/
public double walkInDefaultOrder(final RealVectorPreservingVisitor visitor) {
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> final int dim = getDimension();
visitor.start(dim, 0, dim - 1);
for (int i = 0; i < dim; i++) {
visitor.visit(i, getEntry(i));
}
return visitor.end();
}
/**
* Visits (but does not alter) some entries of this vector in default order
* (increasing index).
*
* @param visitor visitor to be used to process the entries of this vector
* @param start the index of the first entry to be visited
* @param end the index of the last entry to be visited (inclusive)
* @return the value returned by {@link RealVectorPreservingVisitor#end()}
* at the end of the walk
* @throws NumberIsTooSmallException if {@code end < start}.
* @throws OutOfRangeException if the indices are not valid.
* @since 3.1
*/
public double walkInDefaultOrder(final RealVectorPreservingVisitor visitor,
final int start, final int end)
throws NumberIsTooSmallException, OutOfRangeException {
checkIndices(start, end);
visitor.start(getDimension(), start, end);
for (int i = start; i <= end; i++) {
visitor.visit(i, getEntry(i));
}
return visitor.end();
}
/**
* Visits (but does not alter) all entries of this vector in optimized
* order. The order in which the entries are visited is selected so as to
* lead to the most efficient implementation; it might depend on the
* concrete implementation of this abstract class.
*
* @param visitor the visitor to be used to process the entries of this
* vector
* @return the value returned by {@link RealVectorPreservingVisitor#end()}
* at the end of the walk
* @since 3.1
*/
public double walkInOptimizedOrder(final RealVectorPreservingVisitor visitor) {
return walkInDefaultOrder(visitor);
}
/**
* Visits (but does not alter) some entries of this vector in optimized
* order. The order in which the entries are visited is selected so as to
* lead to the most efficient implementation; it might depend on the
* concrete implementation of this abstract class.
*
* @param visitor visitor to be used to process the entries of this vector
* @param start the index of the first entry to be visited
* @param end the index of the last entry to be visited (inclusive)
* @return the value returned by {@link RealVectorPreservingVisitor#end()}
* at the end of the walk
* @throws NumberIsTooSmallException if {@code end < start}.
* @throws OutOfRangeException if the indices are not valid.
* @since 3.1
*/
public double walkInOptimizedOrder(final RealVectorPreservingVisitor visitor,
final int start, final int end)
throws NumberIsTooSmallException, OutOfRangeException {
return walkInDefaultOrder(visitor, start, end);
}
/**
* Visits (and possibly alters) all entries of this vector in default order
* (increasing index).
*
* @param visitor the visitor to be used to process and modify the entries
* of this vector
* @return the value returned by {@link RealVectorChangingVisitor#end()}
* at the end of the walk
* @since 3.1
*/
public double walkInDefaultOrder(final RealVectorChangingVisitor visitor) {
final int dim = getDimension();
visitor.start(dim, 0, dim - 1);
for (int i = 0; i < dim; i++) {
setEntry(i, visitor.visit(i,
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> getEntry(i)));
}
return visitor.end();
}
/**
* Visits (and possibly alters) some entries of this vector in default order
* (increasing index).
*
* @param visitor visitor to be used to process the entries of this vector
* @param start the index of the first entry to be visited
* @param end the index of the last entry to be visited (inclusive)
* @return the value returned by {@link RealVectorChangingVisitor#end()}
* at the end of the walk
* @throws NumberIsTooSmallException if {@code end < start}.
* @throws OutOfRangeException if the indices are not valid.
* @since 3.1
*/
public double walkInDefaultOrder(final RealVectorChangingVisitor visitor,
final int start, final int end)
throws NumberIsTooSmallException, OutOfRangeException {
checkIndices(start, end);
visitor.start(getDimension(), start, end);
for (int i = start; i <= end; i++) {
setEntry(i, visitor.visit(i, getEntry(i)));
}
return visitor.end();
}
/**
* Visits (and possibly alters) all entries of this vector in optimized
* order. The order in which the entries are visited is selected so as to
* lead to the most efficient implementation; it might depend on the
* concrete implementation of this abstract class.
*
* @param visitor the visitor to be used to process the entries of this
* vector
* @return the value returned by {@link RealVectorChangingVisitor#end()}
* at the end of the walk
* @since 3.1
*/
public double walkInOptimizedOrder(final RealVectorChangingVisitor visitor) {
return walkInDefaultOrder(visitor);
}
/**
* Visits (and possibly change) some entries of this vector in optimized
* order. The order in which the entries are visited is selected so as to
* lead to the most efficient implementation; it might depend on the
* concrete implementation of this abstract class.
*
* @param visitor visitor to be used to process the entries of this vector
* @param start the index of the first entry to be visited
* @param end the index of the last entry to be visited (inclusive)
* @return the value returned by {@link RealVectorChangingVisitor#end()}
* at the end of the walk
* @throws NumberIsTooSmallException if {@code end < start}.
* @throws OutOfRangeException if the indices are not valid.
* @since 3.1
*/
public double walkInOptimizedOrder(final RealVectorChangingVisitor visitor,
final int start, final int end)
throws NumberIsTooSmallException, OutOfRangeException {
return walkInDefaultOrder(visitor, start, end);
}
/** An entry in the vector. */
protected class Entry {
/** Index of this entry. */
private int index;
/** Simple constructor. */
public Entry() {
setIndex(0);
}
/**
* Get the value of the entry.
*
* @return the value of the entry.
*/
public double getValue() {
return getEntry(getIndex());
}
/**
* Set the value of the entry.
*
* @param value New value for the entry.
*/
public void setValue(double value) {
setEntry(getIndex(), value);
}
/**
* Get the index of the entry.
*
* @return the index of the entry.
*/
public int getIndex() {
return index;
}
/**
* Set the index of the entry.
*
* @param index New index for the entry.
*/
public void set
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Index(int index) {
this.index = index;
}
}
/**
* <p>
* Test for the equality of two real vectors. If all coordinates of two real
* vectors are exactly the same, and none are {@code NaN}, the two real
* vectors are considered to be equal. {@code NaN} coordinates are
* considered to affect globally the vector and be equals to each other -
* i.e, if either (or all) coordinates of the real vector are equal to
* {@code NaN}, the real vector is equal to a vector with all {@code NaN}
* coordinates.
* </p>
* <p>
* This method <em>must</em> be overriden by concrete subclasses of
* {@link RealVector} (the current implementation throws an exception).
* </p>
*
* @param other Object to test for equality.
* @return {@code true} if two vector objects are equal, {@code false} if
* {@code other} is null, not an instance of {@code RealVector}, or
* not equal to this {@code RealVector} instance.
* @throws MathUnsupportedOperationException if this method is not
* overridden.
*/
@Override
public boolean equals(Object other)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/**
* {@inheritDoc}. This method <em>must</em> be overriden by concrete
* subclasses of {@link RealVector} (current implementation throws an
* exception).
*
* @throws MathUnsupportedOperationException if this method is not
* overridden.
*/
@Override
public int hashCode() throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/**
* This class should rarely be used, but is here to provide
* a default implementation of sparseIterator(), which is implemented
* by walking over the entries, skipping those whose values are the default one.
*
* Concrete subclasses which are SparseVector implementations should
* make their own sparse iterator, rather than using this one.
*
* This implementation might be useful for ArrayRealVector, when expensive
* operations which preserve the default value are to be done on the entries,
* and the fraction of non-default values is small (i.e. someone took a
* SparseVector, and passed it into the copy-constructor of ArrayRealVector)
*
* @deprecated As of 3.1, this class is deprecated, see
* <a href="https://issues.apache.org/jira/browse/MATH-875">JIRA MATH-875</a>.
* This class will be completely removed in 4.0.
*/
@Deprecated
protected class SparseEntryIterator implements Iterator<Entry> {
/** Dimension of the vector. */
private final int dim;
/** Last entry returned by {@link #next()}. */
private Entry current;
/** Next entry for {@link #next()} to return. */
private Entry next;
/** Simple constructor. */
protected SparseEntryIterator() {
dim = getDimension();
current = new Entry();
next = new Entry();
if (next.getValue() == 0) {
advance(next);
}
}
/**
* Advance an entry up to the next nonzero one.
*
* @param e entry to advance.
*/
protected void advance(Entry e) {
if (e == null) {
return;
}
do {
e.setIndex(e.getIndex() + 1);
} while (e.getIndex() < dim && e.getValue() == 0);
if (e.getIndex() >= dim) {
e.setIndex(-1);
}
}
/** {@inheritDoc} */
public boolean hasNext()
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>ArithmeticException {
return v.unitVector();
}
/**
* {@inheritDoc}
*
* @throws MathUnsupportedOperationException in all
* circumstances.
*/
@Override
public void unitize() throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public RealMatrix outerProduct(RealVector w) {
return v.outerProduct(w);
}
/** {@inheritDoc} */
@Override
public double getEntry(int index) throws OutOfRangeException {
return v.getEntry(index);
}
/**
* {@inheritDoc}
*
* @throws MathUnsupportedOperationException in all
* circumstances.
*/
@Override
public void setEntry(int index, double value)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/**
* {@inheritDoc}
*
* @throws MathUnsupportedOperationException in all
* circumstances.
*/
@Override
public void addToEntry(int index, double value)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public int getDimension() {
return v.getDimension();
}
/** {@inheritDoc} */
@Override
public RealVector append(RealVector w) {
return v.append(w);
}
/** {@inheritDoc} */
@Override
public RealVector append(double d) {
return v.append(d);
}
/** {@inheritDoc} */
@Override
public RealVector getSubVector(int index, int n)
throws OutOfRangeException, NotPositiveException {
return v.getSubVector(index, n);
}
/**
* {@inheritDoc}
*
* @throws MathUnsupportedOperationException in all
* circumstances.
*/
@Override
public void setSubVector(int index, RealVector w)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/**
* {@inheritDoc}
*
* @throws MathUnsupportedOperationException in all
* circumstances.
*/
@Override
public void set(double value)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public double[] toArray() {
return v.toArray();
}
/** {@inheritDoc} */
@Override
public boolean isNaN() {
return v.isNaN();
}
/** {@inheritDoc} */
@Override
public boolean isInfinite() {
return v.isInfinite();
}
/** {@inheritDoc} */
@Override
public RealVector combine(double a, double b, RealVector y)
throws DimensionMismatchException {
return v.combine(a, b, y);
}
/**
* {@inheritDoc}
*
* @throws MathUnsupportedOperationException in all
* circumstances.
*/
@Override
public RealVector combineToSelf(double a, double b, RealVector y)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/** An entry in the vector. */
class UnmodifiableEntry extends Entry {
/** {@inheritDoc} */
@Override
public double getValue() {
return v.getEntry(getIndex());
}
/**
* {@inheritDoc}
*
* @throws MathUnsupportedOperationException in all
* circumstances.
*/
@Override
public void setValue(double value)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
}
};
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>li>
* <li>{@link #nextUp(double)}</li>
* <li>{@link #scalb(double, int)}</li>
* <li>{@link #copySign(float, float)}</li>
* <li>{@link #getExponent(float)}</li>
* <li>{@link #nextAfter(float,double)}</li>
* <li>{@link #nextUp(float)}</li>
* <li>{@link #scalb(float, int)}</li>
* </ul>
* </p>
* @version $Id$
* @since 2.2
*/
public class FastMath {
/** Archimede's constant PI, ratio of circle circumference to diameter. */
public static final double PI = 105414357.0 / 33554432.0 + 1.984187159361080883e-9;
/** Napier's constant e, base of the natural logarithm. */
public static final double E = 2850325.0 / 1048576.0 + 8.254840070411028747e-8;
/** Index of exp(0) in the array of integer exponentials. */
static final int EXP_INT_TABLE_MAX_INDEX = 750;
/** Length of the array of integer exponentials. */
static final int EXP_INT_TABLE_LEN = EXP_INT_TABLE_MAX_INDEX * 2;
/** Logarithm table length. */
static final int LN_MANT_LEN = 1024;
/** Exponential fractions table length. */
static final int EXP_FRAC_TABLE_LEN = 1025; // 0, 1/1024, ... 1024/1024
/** StrictMath.log(Double.MAX_VALUE): {@value} */
private static final double LOG_MAX_VALUE = StrictMath.log(Double.MAX_VALUE);
/** Indicator for tables initialization.
* <p>
* This compile-time constant should be set to true only if one explicitly
* wants to compute the tables at class loading time instead of using the
* already computed ones provided as literal arrays below.
* </p>
*/
private static final boolean RECOMPUTE_TABLES_AT_RUNTIME = false;
/** log(2) (high bits). */
private static final double LN_2_A = 0.693147063255310059;
/** log(2) (low bits). */
private static final double LN_2_B = 1.17304635250823482e-7;
/** Coefficients for log, when input 0.99 < x < 1.01. */
private static final double LN_QUICK_COEF[][] = {
{1.0, 5.669184079525E-24},
{-0.25, -0.25},
{0.3333333134651184, 1.986821492305628E-8},
{-0.25, -6.663542893624021E-14},
{0.19999998807907104, 1.
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> static final double F_7_8 = 7d / 8d;
/** Constant: {@value}. */
private static final double F_5_6 = 5d / 6d;
/** Constant: {@value}. */
private static final double F_1_2 = 1d / 2d;
/** Constant: {@value}. */
private static final double F_1_4 = 1d / 4d;
/**
* Private Constructor
*/
private FastMath() {}
// Generic helper methods
/**
* Get the high order bits from the mantissa.
* Equivalent to adding and subtracting HEX_40000 but also works for very large numbers
*
* @param d the value to split
* @return the high order part of the mantissa
*/
private static double doubleHighPart(double d) {
if (d > -Precision.SAFE_MIN && d < Precision.SAFE_MIN){
return d; // These are un-normalised - don't try to convert
}
long xl = Double.doubleToLongBits(d);
xl = xl & MASK_30BITS; // Drop low order bits
return Double.longBitsToDouble(xl);
}
/** Compute the square root of a number.
* <p><b>Note:</b> this implementation currently delegates to {@link Math#sqrt}
* @param a number on which evaluation is done
* @return square root of a
*/
public static double sqrt(final double a) {
return Math.sqrt(a);
}
/** Compute the hyperbolic cosine of a number.
* @param x number on which evaluation is done
* @return hyperbolic cosine of x
*/
public static double cosh(double x) {
if (x != x) {
return x;
}
// cosh[z] = (exp(z) + exp(-z))/2
// for numbers with magnitude 20 or so,
// exp(-z) can be ignored in comparison with exp(z)
if (x > 20) {
if (x >= LOG_MAX_VALUE) {
// Avoid overflow (MATH-905).
final double t = exp(0.5 * x);
return (0.5 * t) * t;
} else {
return 0.5 * exp(x);
}
} else if (x < -20) {
if (x <= -LOG_MAX_VALUE) {
// Avoid overflow (MATH-905).
final double t = exp(-0.5 * x);
return (0.5 * t) * t;
} else {
return 0.5 * exp(-x);
}
}
final double hiPrec[] = new double[2];
if (x < 0.0) {
x = -x;
}
exp(x, 0.0, hiPrec);
double ya = hiPrec[0] + hiPrec[1];
double yb = -(ya - hiPrec[0] - hiPrec[1]);
double temp = ya * HEX_40000000;
double yaa = ya + temp - temp;
double yab = ya - yaa;
// recip = 1/y
double recip = 1.0/ya;
temp = recip * HEX_40000000;
double recipa = recip + temp - temp;
double recipb = recip - recipa;
// Correct for rounding in division
recipb += (1.0 - yaa*recipa - yaa*recipb - yab*
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>;
temp = ratio * HEX_40000000;
double ratioa = ratio + temp - temp;
double ratiob = ratio - ratioa;
// Correct for rounding in division
ratiob += (na - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da;
// Account for nb
ratiob += nb / da;
// Account for db
ratiob += -db * na / da / da;
result = ratioa + ratiob;
}
else {
double hiPrec[] = new double[2];
// tanh(x) = expm1(2x) / (expm1(2x) + 2)
expm1(x*2.0, hiPrec);
double ya = hiPrec[0] + hiPrec[1];
double yb = -(ya - hiPrec[0] - hiPrec[1]);
/* Numerator */
double na = ya;
double nb = yb;
/* Denominator */
double da = 2.0 + ya;
double db = -(da - 2.0 - ya);
double temp = da + yb;
db += -(temp - da - yb);
da = temp;
temp = da * HEX_40000000;
double daa = da + temp - temp;
double dab = da - daa;
// ratio = na/da
double ratio = na/da;
temp = ratio * HEX_40000000;
double ratioa = ratio + temp - temp;
double ratiob = ratio - ratioa;
// Correct for rounding in division
ratiob += (na - daa*ratioa - daa*ratiob - dab*ratioa - dab*ratiob) / da;
// Account for nb
ratiob += nb / da;
// Account for db
ratiob += -db * na / da / da;
result = ratioa + ratiob;
}
if (negate) {
result = -result;
}
return result;
}
/** Compute the inverse hyperbolic cosine of a number.
* @param a number on which evaluation is done
* @return inverse hyperbolic cosine of a
*/
public static double acosh(final double a) {
return FastMath.log(a + FastMath.sqrt(a * a - 1));
}
/** Compute the inverse hyperbolic sine of a number.
* @param a number on which evaluation is done
* @return inverse hyperbolic sine of a
*/
public static double asinh(double a) {
boolean negative = false;
if (a < 0) {
negative = true;
a = -a;
}
double absAsinh;
if (a > 0.167) {
absAsinh = FastMath.log(FastMath.sqrt(a * a + 1) + a);
} else {
final double a2 = a * a;
if (a > 0.097) {
absAsinh = a * (1 - a2 * (F_1_3 - a2 * (F_1_5 - a2 * (F_1_7 - a2 * (F_1_9 - a2 * (F_1_11 - a2 * (F_1_13 - a2 * (F_1_15 - a2 * F_1_17 * F_15_16) * F_13_14) * F_11_12) * F_
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>9_10) * F_7_8) * F_5_6) * F_3_4) * F_1_2);
} else if (a > 0.036) {
absAsinh = a * (1 - a2 * (F_1_3 - a2 * (F_1_5 - a2 * (F_1_7 - a2 * (F_1_9 - a2 * (F_1_11 - a2 * F_1_13 * F_11_12) * F_9_10) * F_7_8) * F_5_6) * F_3_4) * F_1_2);
} else if (a > 0.0036) {
absAsinh = a * (1 - a2 * (F_1_3 - a2 * (F_1_5 - a2 * (F_1_7 - a2 * F_1_9 * F_7_8) * F_5_6) * F_3_4) * F_1_2);
} else {
absAsinh = a * (1 - a2 * (F_1_3 - a2 * F_1_5 * F_3_4) * F_1_2);
}
}
return negative ? -absAsinh : absAsinh;
}
/** Compute the inverse hyperbolic tangent of a number.
* @param a number on which evaluation is done
* @return inverse hyperbolic tangent of a
*/
public static double atanh(double a) {
boolean negative = false;
if (a < 0) {
negative = true;
a = -a;
}
double absAtanh;
if (a > 0.15) {
absAtanh = 0.5 * FastMath.log((1 + a) / (1 - a));
} else {
final double a2 = a * a;
if (a > 0.087) {
absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * (F_1_9 + a2 * (F_1_11 + a2 * (F_1_13 + a2 * (F_1_15 + a2 * F_1_17))))))));
} else if (a > 0.031) {
absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * (F_1_9 + a2 * (F_1_11 + a2 * F_1_13))))));
} else if (a > 0.003) {
absAtanh = a * (1 + a2 * (F_1_3 + a2 * (F_1_5 + a2 * (F_1_7 + a2 * F_1_9))));
} else {
absAtanh = a * (1 + a2 * (F_1_3 + a2 * F_1_5));
}
}
return negative ? -absAtanh : absAtanh;
}
/** Compute the signum of a number.
* The signum is -1 for negative numbers, +1 for positive numbers and 0 otherwise
* @param a number on which evaluation is done
* @return -1.0, -0.0, +0.0,
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>0;
final double xa = x + temp - temp;
final double xb = x - xa;
/* Square it */
double ya = xa*xa;
double yb = xa*xb*2.0 + xb*xb;
/* Subtract from 1 */
ya = -ya;
yb = -yb;
double za = 1.0 + ya;
double zb = -(za - 1.0 - ya);
temp = za + yb;
zb += -(temp - za - yb);
za = temp;
/* Square root */
double y;
y = sqrt(za);
temp = y * HEX_40000000;
ya = y + temp - temp;
yb = y - ya;
/* Extend precision of sqrt */
yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y);
/* Contribution of zb to sqrt */
double dx = zb / (2.0*y);
// Compute ratio r = x/y
double r = x/y;
temp = r * HEX_40000000;
double ra = r + temp - temp;
double rb = r - ra;
rb += (x - ra*ya - ra*yb - rb*ya - rb*yb) / y; // Correct for rounding in division
rb += -x * dx / y / y; // Add in effect additional bits of sqrt.
temp = ra + rb;
rb = -(temp - ra - rb);
ra = temp;
return atan(ra, rb, false);
}
/** Compute the arc cosine of a number.
* @param x number on which evaluation is done
* @return arc cosine of x
*/
public static double acos(double x) {
if (x != x) {
return Double.NaN;
}
if (x > 1.0 || x < -1.0) {
return Double.NaN;
}
if (x == -1.0) {
return Math.PI;
}
if (x == 1.0) {
return 0.0;
}
if (x == 0) {
return Math.PI/2.0;
}
/* Compute acos(x) = atan(sqrt(1-x*x)/x) */
/* Split x */
double temp = x * HEX_40000000;
final double xa = x + temp - temp;
final double xb = x - xa;
/* Square it */
double ya = xa*xa;
double yb = xa*xb*2.0 + xb*xb;
/* Subtract from 1 */
ya = -ya;
yb = -yb;
double za = 1.0 + ya;
double zb = -(za - 1.0 - ya);
temp = za + yb;
zb += -(temp - za - yb);
za = temp;
/* Square root */
double y = sqrt(za);
temp = y * HEX_40000000;
ya = y + temp - temp;
yb = y - ya;
/* Extend precision of sqrt */
yb += (za - ya*ya - 2*ya*yb - yb*yb) / (2.0*y);
/* Contribution of zb to sqrt */
yb += zb / (2.0*y);
y = ya+yb;
yb = -(y - ya - yb);
// Compute ratio r = y/x
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> sides {@code x} and {@code y}
* - sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)<br/>
* avoiding intermediate overflow or underflow.
*
* <ul>
* <li> If either argument is infinite, then the result is positive infinity.</li>
* <li> else, if either argument is NaN then the result is NaN.</li>
* </ul>
*
* @param x a value
* @param y a value
* @return sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>)
*/
public static double hypot(final double x, final double y) {
if (Double.isInfinite(x) || Double.isInfinite(y)) {
return Double.POSITIVE_INFINITY;
} else if (Double.isNaN(x) || Double.isNaN(y)) {
return Double.NaN;
} else {
final int expX = getExponent(x);
final int expY = getExponent(y);
if (expX > expY + 27) {
// y is neglectible with respect to x
return abs(x);
} else if (expY > expX + 27) {
// x is neglectible with respect to y
return abs(y);
} else {
// find an intermediate scale to avoid both overflow and underflow
final int middleExp = (expX + expY) / 2;
// scale parameters without losing precision
final double scaledX = scalb(x, -middleExp);
final double scaledY = scalb(y, -middleExp);
// compute scaled hypotenuse
final double scaledH = sqrt(scaledX * scaledX + scaledY * scaledY);
// remove scaling
return scalb(scaledH, middleExp);
}
}
}
/**
* Computes the remainder as prescribed by the IEEE 754 standard.
* The remainder value is mathematically equal to {@code x - y*n}
* where {@code n} is the mathematical integer closest to the exact mathematical value
* of the quotient {@code x/y}.
* If two mathematical integers are equally close to {@code x/y} then
* {@code n} is the integer that is even.
* <p>
* <ul>
* <li>If either operand is NaN, the result is NaN.</li>
* <li>If the result is not NaN, the sign of the result equals the sign of the dividend.</li>
* <li>If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.</li>
* <li>If the dividend is finite and the divisor is an infinity, the result equals the dividend.</li>
* <li>If the dividend is a zero and the divisor is finite, the result equals the dividend.</li>
* </ul>
* <p><b>Note:</b> this implementation currently delegates to {@link StrictMath#IEEEremainder}
* @param dividend the number to be divided
* @param divisor the number by which to divide
* @return the remainder, rounded
*/
public static double IEEEremainder(double dividend, double divisor) {
return StrictMath.IEEEremainder(dividend, divisor); // TODO provide our own implementation
}
/**
* Returns the first argument with the sign of the second argument.
* A NaN {@code sign} argument is treated as positive.
*
* @param magnitude the value to return
*
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>B", SINE_TABLE_LEN, SINE_TABLE_B);
FastMathCalc.printarray(out, "COSINE_TABLE_A", SINE_TABLE_LEN, COSINE_TABLE_A);
FastMathCalc.printarray(out, "COSINE_TABLE_B", SINE_TABLE_LEN, COSINE_TABLE_B);
FastMathCalc.printarray(out, "TANGENT_TABLE_A", SINE_TABLE_LEN, TANGENT_TABLE_A);
FastMathCalc.printarray(out, "TANGENT_TABLE_B", SINE_TABLE_LEN, TANGENT_TABLE_B);
}
/** Enclose large data table in nested static class so it's only loaded on first access. */
private static class ExpIntTable {
/** Exponential evaluated at integer values,
* exp(x) = expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX].
*/
private static final double[] EXP_INT_TABLE_A;
/** Exponential evaluated at integer values,
* exp(x) = expIntTableA[x + EXP_INT_TABLE_MAX_INDEX] + expIntTableB[x+EXP_INT_TABLE_MAX_INDEX]
*/
private static final double[] EXP_INT_TABLE_B;
static {
if (RECOMPUTE_TABLES_AT_RUNTIME) {
EXP_INT_TABLE_A = new double[FastMath.EXP_INT_TABLE_LEN];
EXP_INT_TABLE_B = new double[FastMath.EXP_INT_TABLE_LEN];
final double tmp[] = new double[2];
final double recip[] = new double[2];
// Populate expIntTable
for (int i = 0; i < FastMath.EXP_INT_TABLE_MAX_INDEX; i++) {
FastMathCalc.expint(i, tmp);
EXP_INT_TABLE_A[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[0];
EXP_INT_TABLE_B[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[1];
if (i != 0) {
// Negative integer powers
FastMathCalc.splitReciprocal(tmp, recip);
EXP_INT_TABLE_A[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[0];
EXP_INT_TABLE_B[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[1];
}
}
} else {
EXP_INT_TABLE_A = FastMathLiteralArrays.loadExpIntA();
EXP_INT_TABLE_B = FastMathLiteralArrays.loadExpIntB();
}
}
}
/** Enclose large data table in nested static class so it's only loaded on first access. */
private static class ExpFracTable {
/** Exponential over the range of 0 - 1 in increments of 2^-10
* exp(x/1024) = expFracTableA[x] + expFracTableB[x].
* 1024 = 2^10
*/
private static final double[] EXP_FRAC_TABLE_A;
/** Exponential over the range of 0 - 1 in increments of 2^-10
* exp(x/1024) = expFracTableA[x] + expFracTableB[x].
*/
private static final double[] EXP_FRAC_
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>TABLE_B;
static {
if (RECOMPUTE_TABLES_AT_RUNTIME) {
EXP_FRAC_TABLE_A = new double[FastMath.EXP_FRAC_TABLE_LEN];
EXP_FRAC_TABLE_B = new double[FastMath.EXP_FRAC_TABLE_LEN];
final double tmp[] = new double[2];
// Populate expFracTable
final double factor = 1d / (EXP_FRAC_TABLE_LEN - 1);
for (int i = 0; i < EXP_FRAC_TABLE_A.length; i++) {
FastMathCalc.slowexp(i * factor, tmp);
EXP_FRAC_TABLE_A[i] = tmp[0];
EXP_FRAC_TABLE_B[i] = tmp[1];
}
} else {
EXP_FRAC_TABLE_A = FastMathLiteralArrays.loadExpFracA();
EXP_FRAC_TABLE_B = FastMathLiteralArrays.loadExpFracB();
}
}
}
/** Enclose large data table in nested static class so it's only loaded on first access. */
private static class lnMant {
/** Extended precision logarithm table over the range 1 - 2 in increments of 2^-10. */
private static final double[][] LN_MANT;
static {
if (RECOMPUTE_TABLES_AT_RUNTIME) {
LN_MANT = new double[FastMath.LN_MANT_LEN][];
// Populate lnMant table
for (int i = 0; i < LN_MANT.length; i++) {
final double d = Double.longBitsToDouble( (((long) i) << 42) | 0x3ff0000000000000L );
LN_MANT[i] = FastMathCalc.slowLog(d);
}
} else {
LN_MANT = FastMathLiteralArrays.loadLnMant();
}
}
}
/** Enclose the Cody/Waite reduction (used in "sin", "cos" and "tan"). */
private static class CodyWaite {
/** k */
private final int finalK;
/** remA */
private final double finalRemA;
/** remB */
private final double finalRemB;
/**
* @param xa Argument.
*/
CodyWaite(double xa) {
// Estimate k.
//k = (int)(xa / 1.5707963267948966);
int k = (int)(xa * 0.6366197723675814);
// Compute remainder.
double remA;
double remB;
while (true) {
double a = -k * 1.570796251296997;
remA = xa + a;
remB = -(remA - xa - a);
a = -k * 7.549789948768648E-8;
double b = remA;
remA = a + b;
remB += -(remA - b - a);
a = -k * 6.123233995736766E-17;
b = remA;
remA = a + b;
remB += -(remA - b - a);
if (remA > 0) {
break;
}
// Remainder is negative, so decrement k and try again.
// This should only
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.linear;
/**
* Interface defining very basic matrix operations.
* @version $Id$
* @since 2.0
*/
public interface AnyMatrix {
/**
* Is this a square matrix?
* @return true if the matrix is square (rowDimension = columnDimension)
*/
boolean isSquare();
/**
* Returns the number of rows in the matrix.
*
* @return rowDimension
*/
int getRowDimension();
/**
* Returns the number of columns in the matrix.
*
* @return columnDimension
*/
int getColumnDimension();
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.linear;
import java.io.Serializable;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.NotStrictlyPositiveException;
import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.exception.MathUnsupportedOperationException;
/**
* Implementation of a diagonal matrix.
* <br/>
* Caveat: This implementation is minimal; it is currently solely aimed
* at solving issue MATH-924. In particular many methods just throw
* {@code MathUnsupportedOperationException}.
*
* @version $Id$
*/
public class DiagonalMatrix extends AbstractRealMatrix
implements Serializable {
/** Serializable version identifier. */
private static final long serialVersionUID = 20121229L;
/** Entries of the diagonal. */
private double[] data;
/**
* Creates a matrix with no data.
*/
public DiagonalMatrix() {}
/**
* Creates a matrix with the supplied dimension.
*
* @param dimension Number of rows and columns in the new matrix.
* @param columnDimension Number of columns in the new matrix.
* @throws NotStrictlyPositiveException if the dimension is
* not positive.
*/
public DiagonalMatrix(final int dimension)
throws NotStrictlyPositiveException {
super(dimension, dimension);
data = new double[dimension];
}
/**
* Creates a matrix using the input array as the underlying data.
* <br/>
* The input array is copied, not referenced.
*
* @param d Data for the new matrix.
*/
public DiagonalMatrix(final double[] d) {
data = d.clone();
}
/**
* Creates a matrix using the input array as the underlying data.
* <br/>
* If an array is built specially in order to be embedded in a
* RealMatrix and not used directly, the {@code copyArray} may be
* set to {@code false}. This will prevent the copying and improve
* performance as no new array will be built and no data will be copied.
*
* @param d Data for new matrix.
* @param copyArray if {@code true}, the input array will be copied,
* otherwise it will be referenced.
*/
public DiagonalMatrix(final double[] d, final boolean copyArray) {
data = copyArray ? d.clone() : d;
}
/**
* {@inheritDoc}
*
* @throws DimensionMismatchException if the requested dimensions are not equal.
*/
@Override
public RealMatrix createMatrix(final int rowDimension,
final int columnDimension)
throws NotStrictlyPositiveException,
DimensionMismatchException {
if (rowDimension != columnDimension) {
throw new DimensionMismatchException(rowDimension, columnDimension);
}
return new
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> DiagonalMatrix(rowDimension);
}
/** {@inheritDoc} */
@Override
public RealMatrix copy() {
return new DiagonalMatrix(data);
}
/**
* Compute the sum of {@code this} and {@code m}.
*
* @param m Matrix to be added.
* @return {@code this + m}.
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as {@code this}.
*/
public DiagonalMatrix add(final DiagonalMatrix m)
throws MatrixDimensionMismatchException {
// Safety check.
MatrixUtils.checkAdditionCompatible(this, m);
final int dim = getRowDimension();
final double[] outData = new double[dim];
for (int i = 0; i < dim; i++) {
outData[i] = data[i] + m.data[i];
}
return new DiagonalMatrix(outData, false);
}
/**
* Returns {@code this} minus {@code m}.
*
* @param m Matrix to be subtracted.
* @return {@code this - m}
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as {@code this}.
*/
public DiagonalMatrix subtract(final DiagonalMatrix m)
throws MatrixDimensionMismatchException {
MatrixUtils.checkSubtractionCompatible(this, m);
final int dim = getRowDimension();
final double[] outData = new double[dim];
for (int i = 0; i < dim; i++) {
outData[i] = data[i] - m.data[i];
}
return new DiagonalMatrix(outData, false);
}
/**
* Returns the result of postmultiplying {@code this} by {@code m}.
*
* @param m matrix to postmultiply by
* @return {@code this * m}
* @throws DimensionMismatchException if
* {@code columnDimension(this) != rowDimension(m)}
*/
public DiagonalMatrix multiply(final DiagonalMatrix m)
throws DimensionMismatchException {
MatrixUtils.checkMultiplicationCompatible(this, m);
final int dim = getRowDimension();
final double[] outData = new double[dim];
for (int i = 0; i < dim; i++) {
outData[i] = data[i] * m.data[i];
}
return new DiagonalMatrix(outData, false);
}
/**
* Returns the result of postmultiplying {@code this} by {@code m}.
*
* @param m matrix to postmultiply by
* @return {@code this * m}
* @throws DimensionMismatchException if
* {@code columnDimension(this) != rowDimension(m)}
*/
public RealMatrix multiply(final RealMatrix m)
throws DimensionMismatchException {
if (m instanceof DiagonalMatrix) {
return multiply((DiagonalMatrix) m);
} else {
MatrixUtils.checkMultiplicationCompatible(this, m);
final int nRows = m.getRowDimension();
final int nCols = m.getColumnDimension();
final double[][] product = new double[nRows][nCols];
for (int r = 0; r < nRows; r++) {
for (int c = 0; c < nCols; c++) {
product[r][c] = data[r] * m.getEntry(r, c);
}
}
return new Array2DRowRealMatrix(product, false);
}
}
/** {@inheritDoc} */
@Override
public double[][] getData() {
final int dim = getRowDimension();
final double[][] out = new double[dim][dim];
for
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> (int i = 0; i < dim; i++) {
out[i][i] = data[i];
}
return out;
}
/**
* Gets a reference to the underlying data array.
*
* @return 1-dimensional array of entries.
*/
public double[] getDataRef() {
return data;
}
/**
* @throws MathUnsupportedOperationException
*/
@Override
public void setSubMatrix(final double[][] subMatrix,
final int row,
final int column)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public double getEntry(final int row, final int column)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
return row == column ? data[row] : 0;
}
/** {@inheritDoc}
* @throws MathUnsupportedOperationException if {@code row != column}.
*/
@Override
public void setEntry(final int row, final int column, final double value)
throws OutOfRangeException,
MathUnsupportedOperationException {
if (row != column) {
throw new MathUnsupportedOperationException();
}
MatrixUtils.checkMatrixIndex(this, row, column);
data[row] = value;
}
/** {@inheritDoc}
* @throws MathUnsupportedOperationException if {@code row != column}.
*/
@Override
public void addToEntry(final int row,
final int column,
final double increment)
throws OutOfRangeException,
MathUnsupportedOperationException {
if (row != column) {
throw new MathUnsupportedOperationException();
}
MatrixUtils.checkMatrixIndex(this, row, column);
data[row] += increment;
}
/** {@inheritDoc}
* @throws MathUnsupportedOperationException if {@code row != column}.
*/
@Override
public void multiplyEntry(final int row,
final int column,
final double factor)
throws OutOfRangeException,
MathUnsupportedOperationException {
if (row != column) {
throw new MathUnsupportedOperationException();
}
MatrixUtils.checkMatrixIndex(this, row, column);
data[row] *= factor;
}
/** {@inheritDoc} */
@Override
public int getRowDimension() {
return data == null ? 0 : data.length;
}
/** {@inheritDoc} */
@Override
public int getColumnDimension() {
return getRowDimension();
}
/** {@inheritDoc} */
@Override
public double[] operate(final double[] v)
throws DimensionMismatchException {
return multiply(new DiagonalMatrix(v, false)).getDataRef();
}
/** {@inheritDoc} */
@Override
public double[] preMultiply(final double[] v)
throws DimensionMismatchException {
return operate(v);
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixChangingVisitor visitor)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws MathUnsupportedOperationException {
throw new MathUnsupportedOperationException();
}
/** {@inheritDoc} */
@
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>,MultivariateVectorFunction,OptimizationData[])
* optimize} method and just before {@link #doOptimize()}.
*
* @since 3.1
*/
protected void setUp() {
// XXX Temporary code until the new internal data is used everywhere.
final int dim = target.length;
weight = new double[dim];
for (int i = 0; i < dim; i++) {
weight[i] = weightMatrix.getEntry(i, i);
}
}
/**
* Scans the list of (required and optional) optimization data that
* characterize the problem.
*
* @param optData Optimization data. The following data will be looked for:
* <ul>
* <li>{@link Target}</li>
* <li>{@link Weight}</li>
* <li>{@link InitialGuess}</li>
* </ul>
*/
private void parseOptimizationData(OptimizationData... optData) {
// The existing values (as set by the previous call) are reused if
// not provided in the argument list.
for (OptimizationData data : optData) {
if (data instanceof Target) {
target = ((Target) data).getTarget();
continue;
}
if (data instanceof Weight) {
weightMatrix = ((Weight) data).getWeight();
continue;
}
if (data instanceof InitialGuess) {
start = ((InitialGuess) data).getInitialGuess();
continue;
}
}
}
/**
* Check parameters consistency.
*
* @throws DimensionMismatchException if {@link #target} and
* {@link #weightMatrix} have inconsistent dimensions.
*/
private void checkParameters() {
if (target.length != weightMatrix.getColumnDimension()) {
throw new DimensionMismatchException(target.length,
weightMatrix.getColumnDimension());
}
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> * @see #createBlocksLayout(int, int)
* @see #toBlocksLayout(double[][])
* @see #BlockRealMatrix(double[][])
*/
public BlockRealMatrix(final int rows, final int columns,
final double[][] blockData, final boolean copyArray)
throws DimensionMismatchException, NotStrictlyPositiveException {
super(rows, columns);
this.rows = rows;
this.columns = columns;
// number of blocks
blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE;
blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE;
if (copyArray) {
// allocate storage blocks, taking care of smaller ones at right and bottom
blocks = new double[blockRows * blockColumns][];
} else {
// reference existing array
blocks = blockData;
}
int index = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock, ++index) {
if (blockData[index].length != iHeight * blockWidth(jBlock)) {
throw new DimensionMismatchException(blockData[index].length,
iHeight * blockWidth(jBlock));
}
if (copyArray) {
blocks[index] = blockData[index].clone();
}
}
}
}
/**
* Convert a data array from raw layout to blocks layout.
* <p>
* Raw layout is the straightforward layout where element at row i and
* column j is in array element <code>rawData[i][j]</code>. Blocks layout
* is the layout used in {@link BlockRealMatrix} instances, where the matrix
* is split in square blocks (except at right and bottom side where blocks may
* be rectangular to fit matrix size) and each block is stored in a flattened
* one-dimensional array.
* </p>
* <p>
* This method creates an array in blocks layout from an input array in raw layout.
* It can be used to provide the array argument of the {@link
* #BlockRealMatrix(int, int, double[][], boolean)} constructor.
* </p>
* @param rawData Data array in raw layout.
* @return a new data array containing the same entries but in blocks layout.
* @throws DimensionMismatchException if {@code rawData} is not rectangular.
* @see #createBlocksLayout(int, int)
* @see #BlockRealMatrix(int, int, double[][], boolean)
*/
public static double[][] toBlocksLayout(final double[][] rawData)
throws DimensionMismatchException {
final int rows = rawData.length;
final int columns = rawData[0].length;
final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE;
final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE;
// safety checks
for (int i = 0; i < rawData.length; ++i) {
final int length = rawData[i].length;
if (length != columns) {
throw new DimensionMismatchException(columns, length);
}
}
// convert array
final double[][] blocks = new double[blockRows * blockColumns][];
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
final int i
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Height = pEnd - pStart;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final int jWidth = qEnd - qStart;
// allocate new block
final double[] block = new double[iHeight * jWidth];
blocks[blockIndex] = block;
// copy data
int index = 0;
for (int p = pStart; p < pEnd; ++p) {
System.arraycopy(rawData[p], qStart, block, index, jWidth);
index += jWidth;
}
++blockIndex;
}
}
return blocks;
}
/**
* Create a data array in blocks layout.
* <p>
* This method can be used to create the array argument of the {@link
* #BlockRealMatrix(int, int, double[][], boolean)} constructor.
* </p>
* @param rows Number of rows in the new matrix.
* @param columns Number of columns in the new matrix.
* @return a new data array in blocks layout.
* @see #toBlocksLayout(double[][])
* @see #BlockRealMatrix(int, int, double[][], boolean)
*/
public static double[][] createBlocksLayout(final int rows, final int columns) {
final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE;
final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE;
final double[][] blocks = new double[blockRows * blockColumns][];
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
final int iHeight = pEnd - pStart;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final int jWidth = qEnd - qStart;
blocks[blockIndex] = new double[iHeight * jWidth];
++blockIndex;
}
}
return blocks;
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix createMatrix(final int rowDimension,
final int columnDimension)
throws NotStrictlyPositiveException {
return new BlockRealMatrix(rowDimension, columnDimension);
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix copy() {
// create an empty matrix
BlockRealMatrix copied = new BlockRealMatrix(rows, columns);
// copy the blocks
for (int i = 0; i < blocks.length; ++i) {
System.arraycopy(blocks[i], 0, copied.blocks[i], 0, blocks[i].length);
}
return copied;
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix add(final RealMatrix m)
throws MatrixDimensionMismatchException {
try {
return add((BlockRealMatrix) m);
} catch (ClassCastException cce) {
// safety check
MatrixUtils.checkAdditionCompatible(this, m);
final BlockRealMatrix out = new BlockRealMatrix(rows, columns);
// perform addition block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
// perform addition on the current block
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q) {
outBlock[k] = tBlock[k] + m.getEntry(p, q);
++k;
}
}
// go to next block
++blockIndex;
}
}
return out;
}
}
/**
* Compute the sum of this matrix and {@code m}.
*
* @param m Matrix to be added.
* @return {@code this} + m.
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as this matrix.
*/
public BlockRealMatrix add(final BlockRealMatrix m)
throws MatrixDimensionMismatchException {
// safety check
MatrixUtils.checkAdditionCompatible(this, m);
final BlockRealMatrix out = new BlockRealMatrix(rows, columns);
// perform addition block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
final double[] mBlock = m.blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k] + mBlock[k];
}
}
return out;
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix subtract(final RealMatrix m)
throws MatrixDimensionMismatchException {
try {
return subtract((BlockRealMatrix) m);
} catch (ClassCastException cce) {
// safety check
MatrixUtils.checkSubtractionCompatible(this, m);
final BlockRealMatrix out = new BlockRealMatrix(rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
// perform subtraction on the current block
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q) {
outBlock[k] = tBlock[k] - m.getEntry(p, q);
++k;
}
}
// go to next block
++blockIndex;
}
}
return out;
}
}
/**
* Subtract {@code m} from this matrix.
*
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> * @param m Matrix to be subtracted.
* @return {@code this} - m.
* @throws MatrixDimensionMismatchException if {@code m} is not the
* same size as this matrix.
*/
public BlockRealMatrix subtract(final BlockRealMatrix m)
throws MatrixDimensionMismatchException {
// safety check
MatrixUtils.checkSubtractionCompatible(this, m);
final BlockRealMatrix out = new BlockRealMatrix(rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
final double[] mBlock = m.blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k] - mBlock[k];
}
}
return out;
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix scalarAdd(final double d) {
final BlockRealMatrix out = new BlockRealMatrix(rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k] + d;
}
}
return out;
}
/** {@inheritDoc} */
@Override
public RealMatrix scalarMultiply(final double d) {
final BlockRealMatrix out = new BlockRealMatrix(rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k] * d;
}
}
return out;
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix multiply(final RealMatrix m)
throws DimensionMismatchException {
try {
return multiply((BlockRealMatrix) m);
} catch (ClassCastException cce) {
// safety check
MatrixUtils.checkMultiplicationCompatible(this, m);
final BlockRealMatrix out = new BlockRealMatrix(rows, m.getColumnDimension());
// perform multiplication block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, m.getColumnDimension());
// select current block
final double[] outBlock = out.blocks[blockIndex];
// perform multiplication on current block
for (int kBlock = 0; kBlock < blockColumns; ++kBlock) {
final int kWidth = blockWidth(kBlock);
final double[] tBlock = blocks[iBlock * blockColumns + kBlock];
final int rStart =
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> kBlock * BLOCK_SIZE;
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
final int lStart = (p - pStart) * kWidth;
final int lEnd = lStart + kWidth;
for (int q = qStart; q < qEnd; ++q) {
double sum = 0;
int r = rStart;
for (int l = lStart; l < lEnd; ++l) {
sum += tBlock[l] * m.getEntry(r, q);
++r;
}
outBlock[k] += sum;
++k;
}
}
}
// go to next block
++blockIndex;
}
}
return out;
}
}
/**
* Returns the result of postmultiplying this by {@code m}.
*
* @param m Matrix to postmultiply by.
* @return {@code this} * m.
* @throws DimensionMismatchException if the matrices are not compatible.
*/
public BlockRealMatrix multiply(BlockRealMatrix m)
throws DimensionMismatchException {
// safety check
MatrixUtils.checkMultiplicationCompatible(this, m);
final BlockRealMatrix out = new BlockRealMatrix(rows, m.columns);
// perform multiplication block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
final int jWidth = out.blockWidth(jBlock);
final int jWidth2 = jWidth + jWidth;
final int jWidth3 = jWidth2 + jWidth;
final int jWidth4 = jWidth3 + jWidth;
// select current block
final double[] outBlock = out.blocks[blockIndex];
// perform multiplication on current block
for (int kBlock = 0; kBlock < blockColumns; ++kBlock) {
final int kWidth = blockWidth(kBlock);
final double[] tBlock = blocks[iBlock * blockColumns + kBlock];
final double[] mBlock = m.blocks[kBlock * m.blockColumns + jBlock];
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
final int lStart = (p - pStart) * kWidth;
final int lEnd = lStart + kWidth;
for (int nStart = 0; nStart < jWidth; ++nStart) {
double sum = 0;
int l = lStart;
int n = nStart;
while (l < lEnd - 3) {
sum += tBlock[l] * mBlock[n] +
tBlock[l + 1] * mBlock[n + jWidth] +
tBlock[l + 2] * mBlock[n + jWidth2] +
tBlock[l + 3] * mBlock[n + jWidth3];
l += 4;
n += jWidth4;
}
while (l < lEnd) {
sum += tBlock[l++] * mBlock[n];
n += jWidth;
}
outBlock[k] += sum;
++k;
}
}
}
// go to next block
++blockIndex;
}
}
return out;
}
/** {@inheritDoc} */
@Override
public double[][] getData() {
final
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> double[][] data = new double[getRowDimension()][getColumnDimension()];
final int lastColumns = columns - (blockColumns - 1) * BLOCK_SIZE;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
int regularPos = 0;
int lastPos = 0;
for (int p = pStart; p < pEnd; ++p) {
final double[] dataP = data[p];
int blockIndex = iBlock * blockColumns;
int dataPos = 0;
for (int jBlock = 0; jBlock < blockColumns - 1; ++jBlock) {
System.arraycopy(blocks[blockIndex++], regularPos, dataP, dataPos, BLOCK_SIZE);
dataPos += BLOCK_SIZE;
}
System.arraycopy(blocks[blockIndex], lastPos, dataP, dataPos, lastColumns);
regularPos += BLOCK_SIZE;
lastPos += lastColumns;
}
}
return data;
}
/** {@inheritDoc} */
@Override
public double getNorm() {
final double[] colSums = new double[BLOCK_SIZE];
double maxColSum = 0;
for (int jBlock = 0; jBlock < blockColumns; jBlock++) {
final int jWidth = blockWidth(jBlock);
Arrays.fill(colSums, 0, jWidth, 0.0);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int j = 0; j < jWidth; ++j) {
double sum = 0;
for (int i = 0; i < iHeight; ++i) {
sum += FastMath.abs(block[i * jWidth + j]);
}
colSums[j] += sum;
}
}
for (int j = 0; j < jWidth; ++j) {
maxColSum = FastMath.max(maxColSum, colSums[j]);
}
}
return maxColSum;
}
/** {@inheritDoc} */
@Override
public double getFrobeniusNorm() {
double sum2 = 0;
for (int blockIndex = 0; blockIndex < blocks.length; ++blockIndex) {
for (final double entry : blocks[blockIndex]) {
sum2 += entry * entry;
}
}
return FastMath.sqrt(sum2);
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix getSubMatrix(final int startRow, final int endRow,
final int startColumn,
final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
// safety checks
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
// create the output matrix
final BlockRealMatrix out =
new BlockRealMatrix(endRow - startRow + 1, endColumn - startColumn + 1);
// compute blocks shifts
final int blockStartRow = startRow / BLOCK_SIZE;
final int rowsShift = startRow % BLOCK_SIZE;
final int blockStartColumn = startColumn / BLOCK_SIZE;
final int columnsShift = startColumn % BLOCK_SIZE;
// perform extraction block-wise, to ensure good cache behavior
int pBlock = blockStartRow;
for (int iBlock = 0; iBlock
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> * @param srcWidth source block width ({@link #BLOCK_SIZE} or smaller)
* @param srcStartRow start row in the source block
* @param srcEndRow end row (exclusive) in the source block
* @param srcStartColumn start column in the source block
* @param srcEndColumn end column (exclusive) in the source block
* @param dstBlock destination block
* @param dstWidth destination block width ({@link #BLOCK_SIZE} or smaller)
* @param dstStartRow start row in the destination block
* @param dstStartColumn start column in the destination block
*/
private void copyBlockPart(final double[] srcBlock, final int srcWidth,
final int srcStartRow, final int srcEndRow,
final int srcStartColumn, final int srcEndColumn,
final double[] dstBlock, final int dstWidth,
final int dstStartRow, final int dstStartColumn) {
final int length = srcEndColumn - srcStartColumn;
int srcPos = srcStartRow * srcWidth + srcStartColumn;
int dstPos = dstStartRow * dstWidth + dstStartColumn;
for (int srcRow = srcStartRow; srcRow < srcEndRow; ++srcRow) {
System.arraycopy(srcBlock, srcPos, dstBlock, dstPos, length);
srcPos += srcWidth;
dstPos += dstWidth;
}
}
/** {@inheritDoc} */
@Override
public void setSubMatrix(final double[][] subMatrix, final int row,
final int column)
throws OutOfRangeException, NoDataException, NullArgumentException,
DimensionMismatchException {
// safety checks
MathUtils.checkNotNull(subMatrix);
final int refLength = subMatrix[0].length;
if (refLength == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
final int endRow = row + subMatrix.length - 1;
final int endColumn = column + refLength - 1;
MatrixUtils.checkSubMatrixIndex(this, row, endRow, column, endColumn);
for (final double[] subRow : subMatrix) {
if (subRow.length != refLength) {
throw new DimensionMismatchException(refLength, subRow.length);
}
}
// compute blocks bounds
final int blockStartRow = row / BLOCK_SIZE;
final int blockEndRow = (endRow + BLOCK_SIZE) / BLOCK_SIZE;
final int blockStartColumn = column / BLOCK_SIZE;
final int blockEndColumn = (endColumn + BLOCK_SIZE) / BLOCK_SIZE;
// perform copy block-wise, to ensure good cache behavior
for (int iBlock = blockStartRow; iBlock < blockEndRow; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final int firstRow = iBlock * BLOCK_SIZE;
final int iStart = FastMath.max(row, firstRow);
final int iEnd = FastMath.min(endRow + 1, firstRow + iHeight);
for (int jBlock = blockStartColumn; jBlock < blockEndColumn; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int firstColumn = jBlock * BLOCK_SIZE;
final int jStart = FastMath.max(column, firstColumn);
final int jEnd = FastMath.min(endColumn + 1, firstColumn + jWidth);
final int jLength = jEnd - jStart;
// handle one block, row by row
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = iStart; i < iEnd; ++i) {
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
System.arraycopy(subMatrix[i - row], jStart - column,
block, (i - firstRow) * jWidth + (jStart - firstColumn),
jLength);
}
}
}
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix getRowMatrix(final int row)
throws OutOfRangeException {
MatrixUtils.checkRowIndex(this, row);
final BlockRealMatrix out = new BlockRealMatrix(1, columns);
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int outBlockIndex = 0;
int outIndex = 0;
double[] outBlock = out.blocks[outBlockIndex];
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
final int available = outBlock.length - outIndex;
if (jWidth > available) {
System.arraycopy(block, iRow * jWidth, outBlock, outIndex, available);
outBlock = out.blocks[++outBlockIndex];
System.arraycopy(block, iRow * jWidth, outBlock, 0, jWidth - available);
outIndex = jWidth - available;
} else {
System.arraycopy(block, iRow * jWidth, outBlock, outIndex, jWidth);
outIndex += jWidth;
}
}
return out;
}
/** {@inheritDoc} */
@Override
public void setRowMatrix(final int row, final RealMatrix matrix)
throws OutOfRangeException, MatrixDimensionMismatchException {
try {
setRowMatrix(row, (BlockRealMatrix) matrix);
} catch (ClassCastException cce) {
super.setRowMatrix(row, matrix);
}
}
/**
* Sets the entries in row number <code>row</code>
* as a row matrix. Row indices start at 0.
*
* @param row the row to be set
* @param matrix row matrix (must have one row and the same number of columns
* as the instance)
* @throws OutOfRangeException if the specified row index is invalid.
* @throws MatrixDimensionMismatchException if the matrix dimensions do
* not match one instance row.
*/
public void setRowMatrix(final int row, final BlockRealMatrix matrix)
throws OutOfRangeException, MatrixDimensionMismatchException {
MatrixUtils.checkRowIndex(this, row);
final int nCols = getColumnDimension();
if ((matrix.getRowDimension() != 1) ||
(matrix.getColumnDimension() != nCols)) {
throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
matrix.getColumnDimension(),
1, nCols);
}
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int mBlockIndex = 0;
int mIndex = 0;
double[] mBlock = matrix.blocks[mBlockIndex];
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
final int available = mBlock.length - mIndex;
if (jWidth > available) {
System.arraycopy(mBlock, mIndex, block, iRow * jWidth, available);
mBlock = matrix.blocks[++mBlockIndex];
System
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>.arraycopy(mBlock, 0, block, iRow * jWidth, jWidth - available);
mIndex = jWidth - available;
} else {
System.arraycopy(mBlock, mIndex, block, iRow * jWidth, jWidth);
mIndex += jWidth;
}
}
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix getColumnMatrix(final int column)
throws OutOfRangeException {
MatrixUtils.checkColumnIndex(this, column);
final BlockRealMatrix out = new BlockRealMatrix(rows, 1);
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outBlockIndex = 0;
int outIndex = 0;
double[] outBlock = out.blocks[outBlockIndex];
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
if (outIndex >= outBlock.length) {
outBlock = out.blocks[++outBlockIndex];
outIndex = 0;
}
outBlock[outIndex++] = block[i * jWidth + jColumn];
}
}
return out;
}
/** {@inheritDoc} */
@Override
public void setColumnMatrix(final int column, final RealMatrix matrix)
throws OutOfRangeException, MatrixDimensionMismatchException {
try {
setColumnMatrix(column, (BlockRealMatrix) matrix);
} catch (ClassCastException cce) {
super.setColumnMatrix(column, matrix);
}
}
/**
* Sets the entries in column number <code>column</code>
* as a column matrix. Column indices start at 0.
*
* @param column the column to be set
* @param matrix column matrix (must have one column and the same number of rows
* as the instance)
* @throws OutOfRangeException if the specified column index is invalid.
* @throws MatrixDimensionMismatchException if the matrix dimensions do
* not match one instance column.
*/
void setColumnMatrix(final int column, final BlockRealMatrix matrix)
throws OutOfRangeException, MatrixDimensionMismatchException {
MatrixUtils.checkColumnIndex(this, column);
final int nRows = getRowDimension();
if ((matrix.getRowDimension() != nRows) ||
(matrix.getColumnDimension() != 1)) {
throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
matrix.getColumnDimension(),
nRows, 1);
}
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int mBlockIndex = 0;
int mIndex = 0;
double[] mBlock = matrix.blocks[mBlockIndex];
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
if (mIndex >= mBlock.length) {
mBlock = matrix.blocks[++mBlockIndex];
mIndex = 0;
}
block[i * jWidth + jColumn]
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>();
if (array.length != nCols) {
throw new MatrixDimensionMismatchException(1, array.length, 1, nCols);
}
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int outIndex = 0;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
System.arraycopy(array, outIndex, block, iRow * jWidth, jWidth);
outIndex += jWidth;
}
}
/** {@inheritDoc} */
@Override
public double[] getColumn(final int column) throws OutOfRangeException {
MatrixUtils.checkColumnIndex(this, column);
final double[] out = new double[rows];
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
out[outIndex++] = block[i * jWidth + jColumn];
}
}
return out;
}
/** {@inheritDoc} */
@Override
public void setColumn(final int column, final double[] array)
throws OutOfRangeException, MatrixDimensionMismatchException {
MatrixUtils.checkColumnIndex(this, column);
final int nRows = getRowDimension();
if (array.length != nRows) {
throw new MatrixDimensionMismatchException(array.length, 1, nRows, 1);
}
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
block[i * jWidth + jColumn] = array[outIndex++];
}
}
}
/** {@inheritDoc} */
@Override
public double getEntry(final int row, final int column)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
return blocks[iBlock * blockColumns + jBlock][k];
}
/** {@inheritDoc} */
@Override
public void setEntry(final int row, final int column, final double value)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>(jBlock) +
(column - jBlock * BLOCK_SIZE);
blocks[iBlock * blockColumns + jBlock][k] = value;
}
/** {@inheritDoc} */
@Override
public void addToEntry(final int row, final int column,
final double increment)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
blocks[iBlock * blockColumns + jBlock][k] += increment;
}
/** {@inheritDoc} */
@Override
public void multiplyEntry(final int row, final int column,
final double factor)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
blocks[iBlock * blockColumns + jBlock][k] *= factor;
}
/** {@inheritDoc} */
@Override
public BlockRealMatrix transpose() {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
final BlockRealMatrix out = new BlockRealMatrix(nCols, nRows);
// perform transpose block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockColumns; ++iBlock) {
for (int jBlock = 0; jBlock < blockRows; ++jBlock) {
// transpose current block
final double[] outBlock = out.blocks[blockIndex];
final double[] tBlock = blocks[jBlock * blockColumns + iBlock];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, columns);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, rows);
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
final int lInc = pEnd - pStart;
int l = p - pStart;
for (int q = qStart; q < qEnd; ++q) {
outBlock[k] = tBlock[l];
++k;
l+= lInc;
}
}
// go to next block
++blockIndex;
}
}
return out;
}
/** {@inheritDoc} */
@Override
public int getRowDimension() {
return rows;
}
/** {@inheritDoc} */
@Override
public int getColumnDimension() {
return columns;
}
/** {@inheritDoc} */
@Override
public double[] operate(final double[] v)
throws DimensionMismatchException {
if (v.length != columns) {
throw new DimensionMismatchException(v.length, columns);
}
final double[] out = new double[rows];
// perform multiplication block-wise, to ensure good cache behavior
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final double[] block =
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> blocks[iBlock * blockColumns + jBlock];
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
double sum = 0;
int q = qStart;
while (q < qEnd - 3) {
sum += block[k] * v[q] +
block[k + 1] * v[q + 1] +
block[k + 2] * v[q + 2] +
block[k + 3] * v[q + 3];
k += 4;
q += 4;
}
while (q < qEnd) {
sum += block[k++] * v[q++];
}
out[p] += sum;
}
}
}
return out;
}
/** {@inheritDoc} */
@Override
public double[] preMultiply(final double[] v)
throws DimensionMismatchException {
if (v.length != rows) {
throw new DimensionMismatchException(v.length, rows);
}
final double[] out = new double[columns];
// perform multiplication block-wise, to ensure good cache behavior
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int jWidth2 = jWidth + jWidth;
final int jWidth3 = jWidth2 + jWidth;
final int jWidth4 = jWidth3 + jWidth;
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final double[] block = blocks[iBlock * blockColumns + jBlock];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int q = qStart; q < qEnd; ++q) {
int k = q - qStart;
double sum = 0;
int p = pStart;
while (p < pEnd - 3) {
sum += block[k] * v[p] +
block[k + jWidth] * v[p + 1] +
block[k + jWidth2] * v[p + 2] +
block[k + jWidth3] * v[p + 3];
k += jWidth4;
p += 4;
}
while (p < pEnd) {
sum += block[k] * v[p++];
k += jWidth;
}
out[q] += sum;
}
}
}
return out;
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixChangingVisitor visitor) {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int qStart = jBlock * BLOCK
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final double[] block = blocks[iBlock * blockColumns + jBlock];
int k = (p - pStart) * jWidth;
for (int q = qStart; q < qEnd; ++q) {
block[k] = visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor) {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final double[] block = blocks[iBlock * blockColumns + jBlock];
int k = (p - pStart) * jWidth;
for (int q = qStart; q < qEnd; ++q) {
visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = FastMath.max(startRow, p0);
final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = FastMath.max(startColumn, q0);
final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final double[] block = blocks[iBlock * blockColumns + jBlock];
int k = (p - p0) * jWidth + qStart - q0;
for (int q = qStart; q < qEnd; ++q) {
block[k] = visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = FastMath.max(startRow, p0);
final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = FastMath.max(startColumn, q0);
final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final double[] block = blocks[iBlock * blockColumns + jBlock];
int k = (p - p0) * jWidth + qStart - q0;
for (int q = qStart; q < qEnd; ++q) {
visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor) {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final double[] block = blocks[blockIndex];
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q) {
block[k] = visitor.visit(p, q, block[k]);
++k;
}
}
++blockIndex;
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor) {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final double[] block = blocks[blockIndex];
int k = 0;
for (int p = pStart;
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q) {
visitor.visit(p, q, block[k]);
++k;
}
}
++blockIndex;
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInOptimizedOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn,
final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = FastMath.max(startRow, p0);
final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = FastMath.max(startColumn, q0);
final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int p = pStart; p < pEnd; ++p) {
int k = (p - p0) * jWidth + qStart - q0;
for (int q = qStart; q < qEnd; ++q) {
block[k] = visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInOptimizedOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
final int startColumn,
final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = FastMath.max(startRow, p0);
final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = FastMath.max(startColumn, q0);
final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final double[] block = blocks[iBlock * blockColumns + jBlock];
for (int p = pStart; p < pEnd; ++p) {
int k = (p - p0) * jWidth + qStart - q
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
* ArrayRealVector and not used directly, the {@code copyArray} may be
* set to {@code false}. This will prevent the copying and improve
* performance as no new array will be built and no data will be copied.
*
* @param d Data for the new vector.
* @param copyArray if {@code true}, the input array will be copied,
* otherwise it will be referenced.
* @throws NullArgumentException if {@code d} is {@code null}.
* @see #ArrayRealVector(double[])
*/
public ArrayRealVector(double[] d, boolean copyArray)
throws NullArgumentException {
if (d == null) {
throw new NullArgumentException();
}
data = copyArray ? d.clone() : d;
}
/**
* Construct a vector from part of a array.
*
* @param d Array.
* @param pos Position of first entry.
* @param size Number of entries to copy.
* @throws NullArgumentException if {@code d} is {@code null}.
* @throws NumberIsTooLargeException if the size of {@code d} is less
* than {@code pos + size}.
*/
public ArrayRealVector(double[] d, int pos, int size)
throws NullArgumentException, NumberIsTooLargeException {
if (d == null) {
throw new NullArgumentException();
}
if (d.length < pos + size) {
throw new NumberIsTooLargeException(pos + size, d.length, true);
}
data = new double[size];
System.arraycopy(d, pos, data, 0, size);
}
/**
* Construct a vector from an array.
*
* @param d Array of {@code Double}s.
*/
public ArrayRealVector(Double[] d) {
data = new double[d.length];
for (int i = 0; i < d.length; i++) {
data[i] = d[i].doubleValue();
}
}
/**
* Construct a vector from part of an array.
*
* @param d Array.
* @param pos Position of first entry.
* @param size Number of entries to copy.
* @throws NullArgumentException if {@code d} is {@code null}.
* @throws NumberIsTooLargeException if the size of {@code d} is less
* than {@code pos + size}.
*/
public ArrayRealVector(Double[] d, int pos, int size)
throws NullArgumentException, NumberIsTooLargeException {
if (d == null) {
throw new NullArgumentException();
}
if (d.length < pos + size) {
throw new NumberIsTooLargeException(pos + size, d.length, true);
}
data = new double[size];
for (int i = pos; i < pos + size; i++) {
data[i - pos] = d[i].doubleValue();
}
}
/**
* Construct a vector from another vector, using a deep copy.
*
* @param v vector to copy.
* @throws NullArgumentException if {@code v} is {@code null}.
*/
public ArrayRealVector(RealVector v) throws NullArgumentException {
if (v == null) {
throw new NullArgumentException();
}
data = new double[v.getDimension()];
for (int i = 0; i < data.length; ++i) {
data[i] = v.getEntry(i);
}
}
/**
* Construct a vector from another vector, using a deep copy.
*
* @param v Vector to copy.
* @throws NullArgumentException if {@code v} is {@code null}.
*/
public ArrayRealVector(Array
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>RealVector v) throws NullArgumentException {
this(v, true);
}
/**
* Construct a vector from another vector.
*
* @param v Vector to copy.
* @param deep If {@code true} perform a deep copy, otherwise perform a
* shallow copy.
*/
public ArrayRealVector(ArrayRealVector v, boolean deep) {
data = deep ? v.data.clone() : v.data;
}
/**
* Construct a vector by appending one vector to another vector.
* @param v1 First vector (will be put in front of the new vector).
* @param v2 Second vector (will be put at back of the new vector).
*/
public ArrayRealVector(ArrayRealVector v1, ArrayRealVector v2) {
data = new double[v1.data.length + v2.data.length];
System.arraycopy(v1.data, 0, data, 0, v1.data.length);
System.arraycopy(v2.data, 0, data, v1.data.length, v2.data.length);
}
/**
* Construct a vector by appending one vector to another vector.
* @param v1 First vector (will be put in front of the new vector).
* @param v2 Second vector (will be put at back of the new vector).
*/
public ArrayRealVector(ArrayRealVector v1, RealVector v2) {
final int l1 = v1.data.length;
final int l2 = v2.getDimension();
data = new double[l1 + l2];
System.arraycopy(v1.data, 0, data, 0, l1);
for (int i = 0; i < l2; ++i) {
data[l1 + i] = v2.getEntry(i);
}
}
/**
* Construct a vector by appending one vector to another vector.
* @param v1 First vector (will be put in front of the new vector).
* @param v2 Second vector (will be put at back of the new vector).
*/
public ArrayRealVector(RealVector v1, ArrayRealVector v2) {
final int l1 = v1.getDimension();
final int l2 = v2.data.length;
data = new double[l1 + l2];
for (int i = 0; i < l1; ++i) {
data[i] = v1.getEntry(i);
}
System.arraycopy(v2.data, 0, data, l1, l2);
}
/**
* Construct a vector by appending one vector to another vector.
* @param v1 First vector (will be put in front of the new vector).
* @param v2 Second vector (will be put at back of the new vector).
*/
public ArrayRealVector(ArrayRealVector v1, double[] v2) {
final int l1 = v1.getDimension();
final int l2 = v2.length;
data = new double[l1 + l2];
System.arraycopy(v1.data, 0, data, 0, l1);
System.arraycopy(v2, 0, data, l1, l2);
}
/**
* Construct a vector by appending one vector to another vector.
* @param v1 First vector (will be put in front of the new vector).
* @param v2 Second vector (will be put at back of the new vector).
*/
public ArrayRealVector(double[] v1, ArrayRealVector v2) {
final int l1 = v1.length;
final int
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> l2 = v2.getDimension();
data = new double[l1 + l2];
System.arraycopy(v1, 0, data, 0, l1);
System.arraycopy(v2.data, 0, data, l1, l2);
}
/**
* Construct a vector by appending one vector to another vector.
* @param v1 first vector (will be put in front of the new vector)
* @param v2 second vector (will be put at back of the new vector)
*/
public ArrayRealVector(double[] v1, double[] v2) {
final int l1 = v1.length;
final int l2 = v2.length;
data = new double[l1 + l2];
System.arraycopy(v1, 0, data, 0, l1);
System.arraycopy(v2, 0, data, l1, l2);
}
/** {@inheritDoc} */
@Override
public ArrayRealVector copy() {
return new ArrayRealVector(this, true);
}
/** {@inheritDoc} */
@Override
public ArrayRealVector add(RealVector v)
throws DimensionMismatchException {
if (v instanceof ArrayRealVector) {
final double[] vData = ((ArrayRealVector) v).data;
final int dim = vData.length;
checkVectorDimensions(dim);
ArrayRealVector result = new ArrayRealVector(dim);
double[] resultData = result.data;
for (int i = 0; i < dim; i++) {
resultData[i] = data[i] + vData[i];
}
return result;
} else {
checkVectorDimensions(v);
double[] out = data.clone();
Iterator<Entry> it = v.iterator();
while (it.hasNext()) {
final Entry e = it.next();
out[e.getIndex()] += e.getValue();
}
return new ArrayRealVector(out, false);
}
}
/** {@inheritDoc} */
@Override
public ArrayRealVector subtract(RealVector v)
throws DimensionMismatchException {
if (v instanceof ArrayRealVector) {
final double[] vData = ((ArrayRealVector) v).data;
final int dim = vData.length;
checkVectorDimensions(dim);
ArrayRealVector result = new ArrayRealVector(dim);
double[] resultData = result.data;
for (int i = 0; i < dim; i++) {
resultData[i] = data[i] - vData[i];
}
return result;
} else {
checkVectorDimensions(v);
double[] out = data.clone();
Iterator<Entry> it = v.iterator();
while (it.hasNext()) {
final Entry e = it.next();
out[e.getIndex()] -= e.getValue();
}
return new ArrayRealVector(out, false);
}
}
/** {@inheritDoc} */
@Override
public ArrayRealVector map(UnivariateFunction function) {
return copy().mapToSelf(function);
}
/** {@inheritDoc} */
@Override
public ArrayRealVector mapToSelf(UnivariateFunction function) {
for (int i = 0; i < data.length; i++) {
data[i] = function.value(data[i]);
}
return this;
}
/** {@inheritDoc} */
@Override
public RealVector mapAddToSelf(double d) {
for (int i = 0; i < data.length; i++) {
data[i] = data[i] + d;
}
return this;
}
/** {@inheritDoc} */
@Override
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> public RealVector mapSubtractToSelf(double d) {
for (int i = 0; i < data.length; i++) {
data[i] = data[i] - d;
}
return this;
}
/** {@inheritDoc} */
@Override
public RealVector mapMultiplyToSelf(double d) {
for (int i = 0; i < data.length; i++) {
data[i] = data[i] * d;
}
return this;
}
/** {@inheritDoc} */
@Override
public RealVector mapDivideToSelf(double d) {
for (int i = 0; i < data.length; i++) {
data[i] = data[i] / d;
}
return this;
}
/** {@inheritDoc} */
@Override
public ArrayRealVector ebeMultiply(RealVector v)
throws DimensionMismatchException {
if (v instanceof ArrayRealVector) {
final double[] vData = ((ArrayRealVector) v).data;
final int dim = vData.length;
checkVectorDimensions(dim);
ArrayRealVector result = new ArrayRealVector(dim);
double[] resultData = result.data;
for (int i = 0; i < dim; i++) {
resultData[i] = data[i] * vData[i];
}
return result;
} else {
checkVectorDimensions(v);
double[] out = data.clone();
for (int i = 0; i < data.length; i++) {
out[i] *= v.getEntry(i);
}
return new ArrayRealVector(out, false);
}
}
/** {@inheritDoc} */
@Override
public ArrayRealVector ebeDivide(RealVector v)
throws DimensionMismatchException {
if (v instanceof ArrayRealVector) {
final double[] vData = ((ArrayRealVector) v).data;
final int dim = vData.length;
checkVectorDimensions(dim);
ArrayRealVector result = new ArrayRealVector(dim);
double[] resultData = result.data;
for (int i = 0; i < dim; i++) {
resultData[i] = data[i] / vData[i];
}
return result;
} else {
checkVectorDimensions(v);
double[] out = data.clone();
for (int i = 0; i < data.length; i++) {
out[i] /= v.getEntry(i);
}
return new ArrayRealVector(out, false);
}
}
/**
* Get a reference to the underlying data array.
* This method does not make a fresh copy of the underlying data.
*
* @return the array of entries.
*/
public double[] getDataRef() {
return data;
}
/** {@inheritDoc} */
@Override
public double dotProduct(RealVector v) throws DimensionMismatchException {
if (v instanceof ArrayRealVector) {
final double[] vData = ((ArrayRealVector) v).data;
checkVectorDimensions(vData.length);
double dot = 0;
for (int i = 0; i < data.length; i++) {
dot += data[i] * vData[i];
}
return dot;
}
return super.dotProduct(v);
}
/** {@inheritDoc} */
@Override
public double getNorm() {
double sum = 0;
for (double a : data) {
sum += a * a;
}
return FastMath.sqrt(sum);
}
/** {@inheritDoc} */
@Override
public double getL1Norm() {
double sum = 0;
for
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> (double a : data) {
sum += FastMath.abs(a);
}
return sum;
}
/** {@inheritDoc} */
@Override
public double getLInfNorm() {
double max = 0;
for (double a : data) {
max = FastMath.max(max, FastMath.abs(a));
}
return max;
}
/** {@inheritDoc} */
@Override
public double getDistance(RealVector v) throws DimensionMismatchException {
if (v instanceof ArrayRealVector) {
final double[] vData = ((ArrayRealVector) v).data;
checkVectorDimensions(vData.length);
double sum = 0;
for (int i = 0; i < data.length; ++i) {
final double delta = data[i] - vData[i];
sum += delta * delta;
}
return FastMath.sqrt(sum);
} else {
checkVectorDimensions(v);
double sum = 0;
for (int i = 0; i < data.length; ++i) {
final double delta = data[i] - v.getEntry(i);
sum += delta * delta;
}
return FastMath.sqrt(sum);
}
}
/** {@inheritDoc} */
@Override
public double getL1Distance(RealVector v)
throws DimensionMismatchException {
if (v instanceof ArrayRealVector) {
final double[] vData = ((ArrayRealVector) v).data;
checkVectorDimensions(vData.length);
double sum = 0;
for (int i = 0; i < data.length; ++i) {
final double delta = data[i] - vData[i];
sum += FastMath.abs(delta);
}
return sum;
} else {
checkVectorDimensions(v);
double sum = 0;
for (int i = 0; i < data.length; ++i) {
final double delta = data[i] - v.getEntry(i);
sum += FastMath.abs(delta);
}
return sum;
}
}
/** {@inheritDoc} */
@Override
public double getLInfDistance(RealVector v)
throws DimensionMismatchException {
if (v instanceof ArrayRealVector) {
final double[] vData = ((ArrayRealVector) v).data;
checkVectorDimensions(vData.length);
double max = 0;
for (int i = 0; i < data.length; ++i) {
final double delta = data[i] - vData[i];
max = FastMath.max(max, FastMath.abs(delta));
}
return max;
} else {
checkVectorDimensions(v);
double max = 0;
for (int i = 0; i < data.length; ++i) {
final double delta = data[i] - v.getEntry(i);
max = FastMath.max(max, FastMath.abs(delta));
}
return max;
}
}
/** {@inheritDoc} */
@Override
public RealMatrix outerProduct(RealVector v) {
if (v instanceof ArrayRealVector) {
final double[] vData = ((ArrayRealVector) v).data;
final int m = data.length;
final int n = vData.length;
final RealMatrix out = MatrixUtils.createRealMatrix(m, n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
out.setEntry(i, j, data[i] * vData[j]);
}
}
return out;
} else
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> {
final int m = data.length;
final int n = v.getDimension();
final RealMatrix out = MatrixUtils.createRealMatrix(m, n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
out.setEntry(i, j, data[i] * v.getEntry(j));
}
}
return out;
}
}
/** {@inheritDoc} */
@Override
public double getEntry(int index) throws OutOfRangeException {
try {
return data[index];
} catch (IndexOutOfBoundsException e) {
throw new OutOfRangeException(LocalizedFormats.INDEX, index, 0,
getDimension() - 1);
}
}
/** {@inheritDoc} */
@Override
public int getDimension() {
return data.length;
}
/** {@inheritDoc} */
@Override
public RealVector append(RealVector v) {
try {
return new ArrayRealVector(this, (ArrayRealVector) v);
} catch (ClassCastException cce) {
return new ArrayRealVector(this, v);
}
}
/**
* Construct a vector by appending a vector to this vector.
*
* @param v Vector to append to this one.
* @return a new vector.
*/
public ArrayRealVector append(ArrayRealVector v) {
return new ArrayRealVector(this, v);
}
/** {@inheritDoc} */
@Override
public RealVector append(double in) {
final double[] out = new double[data.length + 1];
System.arraycopy(data, 0, out, 0, data.length);
out[data.length] = in;
return new ArrayRealVector(out, false);
}
/** {@inheritDoc} */
@Override
public RealVector getSubVector(int index, int n)
throws OutOfRangeException, NotPositiveException {
if (n < 0) {
throw new NotPositiveException(LocalizedFormats.NUMBER_OF_ELEMENTS_SHOULD_BE_POSITIVE, n);
}
ArrayRealVector out = new ArrayRealVector(n);
try {
System.arraycopy(data, index, out.data, 0, n);
} catch (IndexOutOfBoundsException e) {
checkIndex(index);
checkIndex(index + n - 1);
}
return out;
}
/** {@inheritDoc} */
@Override
public void setEntry(int index, double value) throws OutOfRangeException {
try {
data[index] = value;
} catch (IndexOutOfBoundsException e) {
checkIndex(index);
}
}
/** {@inheritDoc} */
@Override
public void addToEntry(int index, double increment)
throws OutOfRangeException {
try {
data[index] += increment;
} catch(IndexOutOfBoundsException e){
throw new OutOfRangeException(LocalizedFormats.INDEX,
index, 0, data.length - 1);
}
}
/** {@inheritDoc} */
@Override
public void setSubVector(int index, RealVector v)
throws OutOfRangeException {
if (v instanceof ArrayRealVector) {
setSubVector(index, ((ArrayRealVector) v).data);
} else {
try {
for (int i = index; i < index + v.getDimension(); ++i) {
data[i] = v.getEntry(i - index);
}
} catch (IndexOutOfBoundsException e) {
checkIndex(index);
checkIndex(index + v.getDimension() - 1);
}
}
}
/**
* Set a set of consecutive elements
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>.
*
* @param index Index of first element to be set.
* @param v Vector containing the values to set.
* @throws OutOfRangeException if the index is inconsistent with the vector
* size.
*/
public void setSubVector(int index, double[] v)
throws OutOfRangeException {
try {
System.arraycopy(v, 0, data, index, v.length);
} catch (IndexOutOfBoundsException e) {
checkIndex(index);
checkIndex(index + v.length - 1);
}
}
/** {@inheritDoc} */
@Override
public void set(double value) {
Arrays.fill(data, value);
}
/** {@inheritDoc} */
@Override
public double[] toArray(){
return data.clone();
}
/** {@inheritDoc} */
@Override
public String toString(){
return DEFAULT_FORMAT.format(this);
}
/**
* Check if instance and specified vectors have the same dimension.
*
* @param v Vector to compare instance with.
* @throws DimensionMismatchException if the vectors do not
* have the same dimension.
*/
@Override
protected void checkVectorDimensions(RealVector v)
throws DimensionMismatchException {
checkVectorDimensions(v.getDimension());
}
/**
* Check if instance dimension is equal to some expected value.
*
* @param n Expected dimension.
* @throws DimensionMismatchException if the dimension is
* inconsistent with vector size.
*/
@Override
protected void checkVectorDimensions(int n)
throws DimensionMismatchException {
if (data.length != n) {
throw new DimensionMismatchException(data.length, n);
}
}
/**
* Check if any coordinate of this vector is {@code NaN}.
*
* @return {@code true} if any coordinate of this vector is {@code NaN},
* {@code false} otherwise.
*/
@Override
public boolean isNaN() {
for (double v : data) {
if (Double.isNaN(v)) {
return true;
}
}
return false;
}
/**
* Check whether any coordinate of this vector is infinite and none
* are {@code NaN}.
*
* @return {@code true} if any coordinate of this vector is infinite and
* none are {@code NaN}, {@code false} otherwise.
*/
@Override
public boolean isInfinite() {
if (isNaN()) {
return false;
}
for (double v : data) {
if (Double.isInfinite(v)) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof RealVector)) {
return false;
}
RealVector rhs = (RealVector) other;
if (data.length != rhs.getDimension()) {
return false;
}
if (rhs.isNaN()) {
return this.isNaN();
}
for (int i = 0; i < data.length; ++i) {
if (data[i] != rhs.getEntry(i)) {
return false;
}
}
return true;
}
/**
* {@inheritDoc} All {@code NaN} values have the same hash code.
*/
@Override
public int hashCode() {
if (isNaN()) {
return 9;
}
return MathUtils.hash(data);
}
/** {@inheritDoc} */
@Override
public ArrayRealVector combine(double a, double b, RealVector y)
throws DimensionMismatchException {
return copy().combineToSelf(a, b, y);
}
/** {@
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>inheritDoc} */
@Override
public ArrayRealVector combineToSelf(double a, double b, RealVector y)
throws DimensionMismatchException {
if (y instanceof ArrayRealVector) {
final double[] yData = ((ArrayRealVector) y).data;
checkVectorDimensions(yData.length);
for (int i = 0; i < this.data.length; i++) {
data[i] = a * data[i] + b * yData[i];
}
} else {
checkVectorDimensions(y);
for (int i = 0; i < this.data.length; i++) {
data[i] = a * data[i] + b * y.getEntry(i);
}
}
return this;
}
/** {@inheritDoc} */
@Override
public double walkInDefaultOrder(final RealVectorPreservingVisitor visitor) {
visitor.start(data.length, 0, data.length - 1);
for (int i = 0; i < data.length; i++) {
visitor.visit(i, data[i]);
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInDefaultOrder(final RealVectorPreservingVisitor visitor,
final int start, final int end) throws NumberIsTooSmallException,
OutOfRangeException {
checkIndices(start, end);
visitor.start(data.length, start, end);
for (int i = start; i <= end; i++) {
visitor.visit(i, data[i]);
}
return visitor.end();
}
/**
* {@inheritDoc}
*
* In this implementation, the optimized order is the default order.
*/
@Override
public double walkInOptimizedOrder(final RealVectorPreservingVisitor visitor) {
return walkInDefaultOrder(visitor);
}
/**
* {@inheritDoc}
*
* In this implementation, the optimized order is the default order.
*/
@Override
public double walkInOptimizedOrder(final RealVectorPreservingVisitor visitor,
final int start, final int end) throws NumberIsTooSmallException,
OutOfRangeException {
return walkInDefaultOrder(visitor, start, end);
}
/** {@inheritDoc} */
@Override
public double walkInDefaultOrder(final RealVectorChangingVisitor visitor) {
visitor.start(data.length, 0, data.length - 1);
for (int i = 0; i < data.length; i++) {
data[i] = visitor.visit(i, data[i]);
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInDefaultOrder(final RealVectorChangingVisitor visitor,
final int start, final int end) throws NumberIsTooSmallException,
OutOfRangeException {
checkIndices(start, end);
visitor.start(data.length, start, end);
for (int i = start; i <= end; i++) {
data[i] = visitor.visit(i, data[i]);
}
return visitor.end();
}
/**
* {@inheritDoc}
*
* In this implementation, the optimized order is the default order.
*/
@Override
public double walkInOptimizedOrder(final RealVectorChangingVisitor visitor) {
return walkInDefaultOrder(visitor);
}
/**
* {@inheritDoc}
*
* In this implementation, the optimized order is the default order.
*/
@Override
public double walkInOptimizedOrder(final RealVectorChangingVisitor visitor,
final int start, final int end) throws NumberIsTooSmallException,
OutOfRangeException {
return walkInDefaultOrder(visitor
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> currentPoint = getStartPoint();
final int nC = currentPoint.length; // Number of parameters.
// arrays shared with the other private methods
solvedCols = FastMath.min(nR, nC);
diagR = new double[nC];
jacNorm = new double[nC];
beta = new double[nC];
permutation = new int[nC];
lmDir = new double[nC];
// local point
double delta = 0;
double xNorm = 0;
double[] diag = new double[nC];
double[] oldX = new double[nC];
double[] oldRes = new double[nR];
double[] oldObj = new double[nR];
double[] qtf = new double[nR];
double[] work1 = new double[nC];
double[] work2 = new double[nC];
double[] work3 = new double[nC];
final RealMatrix weightMatrixSqrt = getWeightSquareRoot();
// Evaluate the function at the starting point and calculate its norm.
double[] currentObjective = computeObjectiveValue(currentPoint);
double[] currentResiduals = computeResiduals(currentObjective);
PointVectorValuePair current = new PointVectorValuePair(currentPoint, currentObjective);
double currentCost = computeCost(currentResiduals);
// Outer loop.
lmPar = 0;
boolean firstIteration = true;
int iter = 0;
final ConvergenceChecker<PointVectorValuePair> checker = getConvergenceChecker();
while (true) {
++iter;
final PointVectorValuePair previous = current;
// QR decomposition of the jacobian matrix
qrDecomposition(computeWeightedJacobian(currentPoint));
weightedResidual = weightMatrixSqrt.operate(currentResiduals);
for (int i = 0; i < nR; i++) {
qtf[i] = weightedResidual[i];
}
// compute Qt.res
qTy(qtf);
// now we don't need Q anymore,
// so let jacobian contain the R matrix with its diagonal elements
for (int k = 0; k < solvedCols; ++k) {
int pk = permutation[k];
weightedJacobian[k][pk] = diagR[pk];
}
if (firstIteration) {
// scale the point according to the norms of the columns
// of the initial jacobian
xNorm = 0;
for (int k = 0; k < nC; ++k) {
double dk = jacNorm[k];
if (dk == 0) {
dk = 1.0;
}
double xk = dk * currentPoint[k];
xNorm += xk * xk;
diag[k] = dk;
}
xNorm = FastMath.sqrt(xNorm);
// initialize the step bound delta
delta = (xNorm == 0) ? initialStepBoundFactor : (initialStepBoundFactor * xNorm);
}
// check orthogonality between function vector and jacobian columns
double maxCosine = 0;
if (currentCost != 0) {
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double s = jacNorm[pj];
if (s != 0) {
double sum = 0;
for (int i = 0; i <= j; ++i) {
sum += weightedJacobian[i][pj] * qtf[i];
}
maxCosine = FastMath.max(maxCos
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>ine, FastMath.abs(sum) / (s * currentCost));
}
}
}
if (maxCosine <= orthoTolerance) {
// Convergence has been reached.
setCost(currentCost);
// Update (deprecated) "point" field.
point = current.getPoint();
return current;
}
// rescale if necessary
for (int j = 0; j < nC; ++j) {
diag[j] = FastMath.max(diag[j], jacNorm[j]);
}
// Inner loop.
for (double ratio = 0; ratio < 1.0e-4;) {
// save the state
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
oldX[pj] = currentPoint[pj];
}
final double previousCost = currentCost;
double[] tmpVec = weightedResidual;
weightedResidual = oldRes;
oldRes = tmpVec;
tmpVec = currentObjective;
currentObjective = oldObj;
oldObj = tmpVec;
// determine the Levenberg-Marquardt parameter
determineLMParameter(qtf, delta, diag, work1, work2, work3);
// compute the new point and the norm of the evolution direction
double lmNorm = 0;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
lmDir[pj] = -lmDir[pj];
currentPoint[pj] = oldX[pj] + lmDir[pj];
double s = diag[pj] * lmDir[pj];
lmNorm += s * s;
}
lmNorm = FastMath.sqrt(lmNorm);
// on the first iteration, adjust the initial step bound.
if (firstIteration) {
delta = FastMath.min(delta, lmNorm);
}
// Evaluate the function at x + p and calculate its norm.
currentObjective = computeObjectiveValue(currentPoint);
currentResiduals = computeResiduals(currentObjective);
current = new PointVectorValuePair(currentPoint, currentObjective);
currentCost = computeCost(currentResiduals);
// compute the scaled actual reduction
double actRed = -1.0;
if (0.1 * currentCost < previousCost) {
double r = currentCost / previousCost;
actRed = 1.0 - r * r;
}
// compute the scaled predicted reduction
// and the scaled directional derivative
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double dirJ = lmDir[pj];
work1[j] = 0;
for (int i = 0; i <= j; ++i) {
work1[i] += weightedJacobian[i][pj] * dirJ;
}
}
double coeff1 = 0;
for (int j = 0; j < solvedCols; ++j) {
coeff1 += work1[j] * work1[j];
}
double pc2 = previousCost * previousCost;
coeff1 = coeff1 / pc2;
double coeff2 = lmPar * lmNorm * lmNorm / pc2;
double preRed = coeff1 + 2 * coeff2;
double dirDer = -(coeff1 + coeff2);
// ratio of the actual to the predicted reduction
ratio = (preRed == 0) ? 0 : (actRed / preRed);
// update the step bound
if (ratio <= 0.25) {
double tmp =
(actRed < 0)
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> ? (0.5 * dirDer / (dirDer + 0.5 * actRed)) : 0.5;
if ((0.1 * currentCost >= previousCost) || (tmp < 0.1)) {
tmp = 0.1;
}
delta = tmp * FastMath.min(delta, 10.0 * lmNorm);
lmPar /= tmp;
} else if ((lmPar == 0) || (ratio >= 0.75)) {
delta = 2 * lmNorm;
lmPar *= 0.5;
}
// test for successful iteration.
if (ratio >= 1.0e-4) {
// successful iteration, update the norm
firstIteration = false;
xNorm = 0;
for (int k = 0; k < nC; ++k) {
double xK = diag[k] * currentPoint[k];
xNorm += xK * xK;
}
xNorm = FastMath.sqrt(xNorm);
// tests for convergence.
if (checker != null) {
// we use the vectorial convergence checker
if (checker.converged(iter, previous, current)) {
setCost(currentCost);
// Update (deprecated) "point" field.
point = current.getPoint();
return current;
}
}
} else {
// failed iteration, reset the previous values
currentCost = previousCost;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
currentPoint[pj] = oldX[pj];
}
tmpVec = weightedResidual;
weightedResidual = oldRes;
oldRes = tmpVec;
tmpVec = currentObjective;
currentObjective = oldObj;
oldObj = tmpVec;
// Reset "current" to previous values.
current = new PointVectorValuePair(currentPoint, currentObjective);
}
// Default convergence criteria.
if ((FastMath.abs(actRed) <= costRelativeTolerance &&
preRed <= costRelativeTolerance &&
ratio <= 2.0) ||
delta <= parRelativeTolerance * xNorm) {
setCost(currentCost);
// Update (deprecated) "point" field.
point = current.getPoint();
return current;
}
// tests for termination and stringent tolerances
// (2.2204e-16 is the machine epsilon for IEEE754)
if ((FastMath.abs(actRed) <= 2.2204e-16) && (preRed <= 2.2204e-16) && (ratio <= 2.0)) {
throw new ConvergenceException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE,
costRelativeTolerance);
} else if (delta <= 2.2204e-16 * xNorm) {
throw new ConvergenceException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE,
parRelativeTolerance);
} else if (maxCosine <= 2.2204e-16) {
throw new ConvergenceException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE,
orthoTolerance);
}
}
}
}
/**
* Determine the Levenberg-Marquardt parameter.
* <p>This implementation is a translation in Java of the MINPACK
* <a href="http://www.netlib.org/minpack/lmpar.f">lmpar</a>
* routine.</p>
* <p>This method sets the lmPar
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> and lmDir attributes.</p>
* <p>The authors of the original fortran function are:</p>
* <ul>
* <li>Argonne National Laboratory. MINPACK project. March 1980</li>
* <li>Burton S. Garbow</li>
* <li>Kenneth E. Hillstrom</li>
* <li>Jorge J. More</li>
* </ul>
* <p>Luc Maisonobe did the Java translation.</p>
*
* @param qy array containing qTy
* @param delta upper bound on the euclidean norm of diagR * lmDir
* @param diag diagonal matrix
* @param work1 work array
* @param work2 work array
* @param work3 work array
*/
private void determineLMParameter(double[] qy, double delta, double[] diag,
double[] work1, double[] work2, double[] work3) {
final int nC = weightedJacobian[0].length;
// compute and store in x the gauss-newton direction, if the
// jacobian is rank-deficient, obtain a least squares solution
for (int j = 0; j < rank; ++j) {
lmDir[permutation[j]] = qy[j];
}
for (int j = rank; j < nC; ++j) {
lmDir[permutation[j]] = 0;
}
for (int k = rank - 1; k >= 0; --k) {
int pk = permutation[k];
double ypk = lmDir[pk] / diagR[pk];
for (int i = 0; i < k; ++i) {
lmDir[permutation[i]] -= ypk * weightedJacobian[i][pk];
}
lmDir[pk] = ypk;
}
// evaluate the function at the origin, and test
// for acceptance of the Gauss-Newton direction
double dxNorm = 0;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double s = diag[pj] * lmDir[pj];
work1[pj] = s;
dxNorm += s * s;
}
dxNorm = FastMath.sqrt(dxNorm);
double fp = dxNorm - delta;
if (fp <= 0.1 * delta) {
lmPar = 0;
return;
}
// if the jacobian is not rank deficient, the Newton step provides
// a lower bound, parl, for the zero of the function,
// otherwise set this bound to zero
double sum2;
double parl = 0;
if (rank == solvedCols) {
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
work1[pj] *= diag[pj] / dxNorm;
}
sum2 = 0;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double sum = 0;
for (int i = 0; i < j; ++i) {
sum += weightedJacobian[i][pj] * work1[permutation[i]];
}
double s = (work1[pj] - sum) / diagR[pj];
work1[pj] = s;
sum2 += s * s;
}
parl = fp / (delta * sum2);
}
// calculate an upper bound, paru, for the zero of the function
sum2 = 0
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double sum = 0;
for (int i = 0; i <= j; ++i) {
sum += weightedJacobian[i][pj] * qy[i];
}
sum /= diag[pj];
sum2 += sum * sum;
}
double gNorm = FastMath.sqrt(sum2);
double paru = gNorm / delta;
if (paru == 0) {
// 2.2251e-308 is the smallest positive real for IEE754
paru = 2.2251e-308 / FastMath.min(delta, 0.1);
}
// if the input par lies outside of the interval (parl,paru),
// set par to the closer endpoint
lmPar = FastMath.min(paru, FastMath.max(lmPar, parl));
if (lmPar == 0) {
lmPar = gNorm / dxNorm;
}
for (int countdown = 10; countdown >= 0; --countdown) {
// evaluate the function at the current value of lmPar
if (lmPar == 0) {
lmPar = FastMath.max(2.2251e-308, 0.001 * paru);
}
double sPar = FastMath.sqrt(lmPar);
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
work1[pj] = sPar * diag[pj];
}
determineLMDirection(qy, work1, work2, work3);
dxNorm = 0;
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
double s = diag[pj] * lmDir[pj];
work3[pj] = s;
dxNorm += s * s;
}
dxNorm = FastMath.sqrt(dxNorm);
double previousFP = fp;
fp = dxNorm - delta;
// if the function is small enough, accept the current value
// of lmPar, also test for the exceptional cases where parl is zero
if ((FastMath.abs(fp) <= 0.1 * delta) ||
((parl == 0) && (fp <= previousFP) && (previousFP < 0))) {
return;
}
// compute the Newton correction
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
work1[pj] = work3[pj] * diag[pj] / dxNorm;
}
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
work1[pj] /= work2[j];
double tmp = work1[pj];
for (int i = j + 1; i < solvedCols; ++i) {
work1[permutation[i]] -= weightedJacobian[i][pj] * tmp;
}
}
sum2 = 0;
for (int j = 0; j < solvedCols; ++j) {
double s = work1[permutation[j]];
sum2 += s * s;
}
double correction = fp / (delta * sum2);
// depending on the sign of the function, update parl or paru.
if (fp > 0) {
parl = FastMath.max(parl, lmPar);
} else if (fp < 0) {
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
paru = FastMath.min(paru, lmPar);
}
// compute an improved estimate for lmPar
lmPar = FastMath.max(parl, lmPar + correction);
}
}
/**
* Solve a*x = b and d*x = 0 in the least squares sense.
* <p>This implementation is a translation in Java of the MINPACK
* <a href="http://www.netlib.org/minpack/qrsolv.f">qrsolv</a>
* routine.</p>
* <p>This method sets the lmDir and lmDiag attributes.</p>
* <p>The authors of the original fortran function are:</p>
* <ul>
* <li>Argonne National Laboratory. MINPACK project. March 1980</li>
* <li>Burton S. Garbow</li>
* <li>Kenneth E. Hillstrom</li>
* <li>Jorge J. More</li>
* </ul>
* <p>Luc Maisonobe did the Java translation.</p>
*
* @param qy array containing qTy
* @param diag diagonal matrix
* @param lmDiag diagonal elements associated with lmDir
* @param work work array
*/
private void determineLMDirection(double[] qy, double[] diag,
double[] lmDiag, double[] work) {
// copy R and Qty to preserve input and initialize s
// in particular, save the diagonal elements of R in lmDir
for (int j = 0; j < solvedCols; ++j) {
int pj = permutation[j];
for (int i = j + 1; i < solvedCols; ++i) {
weightedJacobian[i][pj] = weightedJacobian[j][permutation[i]];
}
lmDir[j] = diagR[pj];
work[j] = qy[j];
}
// eliminate the diagonal matrix d using a Givens rotation
for (int j = 0; j < solvedCols; ++j) {
// prepare the row of d to be eliminated, locating the
// diagonal element using p from the Q.R. factorization
int pj = permutation[j];
double dpj = diag[pj];
if (dpj != 0) {
Arrays.fill(lmDiag, j + 1, lmDiag.length, 0);
}
lmDiag[j] = dpj;
// the transformations to eliminate the row of d
// modify only a single element of Qty
// beyond the first n, which is initially zero.
double qtbpj = 0;
for (int k = j; k < solvedCols; ++k) {
int pk = permutation[k];
// determine a Givens rotation which eliminates the
// appropriate element in the current row of d
if (lmDiag[k] != 0) {
final double sin;
final double cos;
double rkk = weightedJacobian[k][pk];
if (FastMath.abs(rkk) < FastMath.abs(lmDiag[k])) {
final double cotan = rkk / lmDiag[k];
sin = 1.0 / FastMath.sqrt(1.0 + cotan * cotan);
cos = sin * cotan;
} else {
final double tan = lmDiag[k] / rkk;
cos = 1.0 / FastMath.sqrt(1.0 + tan * tan);
sin = cos * tan;
}
// compute the modified diagonal element of
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> the tranformations
* are performed in non-increasing columns norms order thanks to columns
* pivoting. The diagonal elements of the R matrix are therefore also in
* non-increasing absolute values order.</p>
*
* @param jacobian Weighted Jacobian matrix at the current point.
* @exception ConvergenceException if the decomposition cannot be performed
*/
private void qrDecomposition(RealMatrix jacobian) throws ConvergenceException {
// Code in this class assumes that the weighted Jacobian is -(W^(1/2) J),
// hence the multiplication by -1.
weightedJacobian = jacobian.scalarMultiply(-1).getData();
final int nR = weightedJacobian.length;
final int nC = weightedJacobian[0].length;
// initializations
for (int k = 0; k < nC; ++k) {
permutation[k] = k;
double norm2 = 0;
for (int i = 0; i < nR; ++i) {
double akk = weightedJacobian[i][k];
norm2 += akk * akk;
}
jacNorm[k] = FastMath.sqrt(norm2);
}
// transform the matrix column after column
for (int k = 0; k < nC; ++k) {
// select the column with the greatest norm on active components
int nextColumn = -1;
double ak2 = Double.NEGATIVE_INFINITY;
for (int i = k; i < nC; ++i) {
double norm2 = 0;
for (int j = k; j < nR; ++j) {
double aki = weightedJacobian[j][permutation[i]];
norm2 += aki * aki;
}
if (Double.isInfinite(norm2) || Double.isNaN(norm2)) {
throw new ConvergenceException(LocalizedFormats.UNABLE_TO_PERFORM_QR_DECOMPOSITION_ON_JACOBIAN,
nR, nC);
}
if (norm2 > ak2) {
nextColumn = i;
ak2 = norm2;
}
}
if (ak2 <= qrRankingThreshold) {
rank = k;
return;
}
int pk = permutation[nextColumn];
permutation[nextColumn] = permutation[k];
permutation[k] = pk;
// choose alpha such that Hk.u = alpha ek
double akk = weightedJacobian[k][pk];
double alpha = (akk > 0) ? -FastMath.sqrt(ak2) : FastMath.sqrt(ak2);
double betak = 1.0 / (ak2 - akk * alpha);
beta[pk] = betak;
// transform the current column
diagR[pk] = alpha;
weightedJacobian[k][pk] -= alpha;
// transform the remaining columns
for (int dk = nC - 1 - k; dk > 0; --dk) {
double gamma = 0;
for (int j = k; j < nR; ++j) {
gamma += weightedJacobian[j][pk] * weightedJacobian[j][permutation[k + dk]];
}
gamma *= betak;
for (int j = k; j < nR; ++j) {
weightedJacobian[j][permutation[k + dk]] -= gamma * weightedJacobian[j][pk];
}
}
}
rank = solvedCols;
}
/**
* Compute the product Qt.y for some Q.R. decomposition.
*
* @param y vector to multiply (will be overwritten with
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> array
* @return a matrix containing the values of the array.
* @throws org.apache.commons.math3.exception.DimensionMismatchException
* if {@code data} is not rectangular (not all rows have the same length).
* @throws NoDataException if a row or column is empty.
* @throws NullArgumentException if either {@code data} or {@code data[0]}
* is {@code null}.
* @see #createFieldMatrix(Field, int, int)
* @since 2.0
*/
public static <T extends FieldElement<T>> FieldMatrix<T> createFieldMatrix(T[][] data)
throws DimensionMismatchException, NoDataException, NullArgumentException {
if (data == null ||
data[0] == null) {
throw new NullArgumentException();
}
return (data.length * data[0].length <= 4096) ?
new Array2DRowFieldMatrix<T>(data) : new BlockFieldMatrix<T>(data);
}
/**
* Returns <code>dimension x dimension</code> identity matrix.
*
* @param dimension dimension of identity matrix to generate
* @return identity matrix
* @throws IllegalArgumentException if dimension is not positive
* @since 1.1
*/
public static RealMatrix createRealIdentityMatrix(int dimension) {
final RealMatrix m = createRealMatrix(dimension, dimension);
for (int i = 0; i < dimension; ++i) {
m.setEntry(i, i, 1.0);
}
return m;
}
/**
* Returns <code>dimension x dimension</code> identity matrix.
*
* @param <T> the type of the field elements
* @param field field to which the elements belong
* @param dimension dimension of identity matrix to generate
* @return identity matrix
* @throws IllegalArgumentException if dimension is not positive
* @since 2.0
*/
public static <T extends FieldElement<T>> FieldMatrix<T>
createFieldIdentityMatrix(final Field<T> field, final int dimension) {
final T zero = field.getZero();
final T one = field.getOne();
@SuppressWarnings("unchecked")
final T[][] d = (T[][]) Array.newInstance(field.getRuntimeClass(), new int[] { dimension, dimension });
for (int row = 0; row < dimension; row++) {
final T[] dRow = d[row];
Arrays.fill(dRow, zero);
dRow[row] = one;
}
return new Array2DRowFieldMatrix<T>(field, d, false);
}
/**
* Returns a diagonal matrix with specified elements.
*
* @param diagonal diagonal elements of the matrix (the array elements
* will be copied)
* @return diagonal matrix
* @since 2.0
*/
public static RealMatrix createRealDiagonalMatrix(final double[] diagonal) {
final RealMatrix m = createRealMatrix(diagonal.length, diagonal.length);
for (int i = 0; i < diagonal.length; ++i) {
m.setEntry(i, i, diagonal[i]);
}
return m;
}
/**
* Returns a diagonal matrix with specified elements.
*
* @param <T> the type of the field elements
* @param diagonal diagonal elements of the matrix (the array elements
* will be copied)
* @return diagonal matrix
* @since 2.0
*/
public static <T extends FieldElement<T>> FieldMatrix<T>
createFieldDiagonalMatrix(final T[] diagonal) {
final FieldMatrix<T> m =
createFieldMatrix(diagonal[0].getField(), diagonal.length,
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> diagonal.length);
for (int i = 0; i < diagonal.length; ++i) {
m.setEntry(i, i, diagonal[i]);
}
return m;
}
/**
* Creates a {@link RealVector} using the data from the input array.
*
* @param data the input data
* @return a data.length RealVector
* @throws NoDataException if {@code data} is empty.
* @throws NullArgumentException if {@code data} is {@code null}.
*/
public static RealVector createRealVector(double[] data)
throws NoDataException, NullArgumentException {
if (data == null) {
throw new NullArgumentException();
}
return new ArrayRealVector(data, true);
}
/**
* Creates a {@link FieldVector} using the data from the input array.
*
* @param <T> the type of the field elements
* @param data the input data
* @return a data.length FieldVector
* @throws NoDataException if {@code data} is empty.
* @throws NullArgumentException if {@code data} is {@code null}.
* @throws ZeroException if {@code data} has 0 elements
*/
public static <T extends FieldElement<T>> FieldVector<T> createFieldVector(final T[] data)
throws NoDataException, NullArgumentException, ZeroException {
if (data == null) {
throw new NullArgumentException();
}
if (data.length == 0) {
throw new ZeroException(LocalizedFormats.VECTOR_MUST_HAVE_AT_LEAST_ONE_ELEMENT);
}
return new ArrayFieldVector<T>(data[0].getField(), data, true);
}
/**
* Create a row {@link RealMatrix} using the data from the input
* array.
*
* @param rowData the input row data
* @return a 1 x rowData.length RealMatrix
* @throws NoDataException if {@code rowData} is empty.
* @throws NullArgumentException if {@code rowData} is {@code null}.
*/
public static RealMatrix createRowRealMatrix(double[] rowData)
throws NoDataException, NullArgumentException {
if (rowData == null) {
throw new NullArgumentException();
}
final int nCols = rowData.length;
final RealMatrix m = createRealMatrix(1, nCols);
for (int i = 0; i < nCols; ++i) {
m.setEntry(0, i, rowData[i]);
}
return m;
}
/**
* Create a row {@link FieldMatrix} using the data from the input
* array.
*
* @param <T> the type of the field elements
* @param rowData the input row data
* @return a 1 x rowData.length FieldMatrix
* @throws NoDataException if {@code rowData} is empty.
* @throws NullArgumentException if {@code rowData} is {@code null}.
*/
public static <T extends FieldElement<T>> FieldMatrix<T>
createRowFieldMatrix(final T[] rowData)
throws NoDataException, NullArgumentException {
if (rowData == null) {
throw new NullArgumentException();
}
final int nCols = rowData.length;
if (nCols == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
final FieldMatrix<T> m = createFieldMatrix(rowData[0].getField(), 1, nCols);
for (int i = 0; i < nCols; ++i) {
m.setEntry(0, i, rowData[i]);
}
return m;
}
/**
* Creates a column
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> {@link RealMatrix} using the data from the input
* array.
*
* @param columnData the input column data
* @return a columnData x 1 RealMatrix
* @throws NoDataException if {@code columnData} is empty.
* @throws NullArgumentException if {@code columnData} is {@code null}.
*/
public static RealMatrix createColumnRealMatrix(double[] columnData)
throws NoDataException, NullArgumentException {
if (columnData == null) {
throw new NullArgumentException();
}
final int nRows = columnData.length;
final RealMatrix m = createRealMatrix(nRows, 1);
for (int i = 0; i < nRows; ++i) {
m.setEntry(i, 0, columnData[i]);
}
return m;
}
/**
* Creates a column {@link FieldMatrix} using the data from the input
* array.
*
* @param <T> the type of the field elements
* @param columnData the input column data
* @return a columnData x 1 FieldMatrix
* @throws NoDataException if {@code data} is empty.
* @throws NullArgumentException if {@code columnData} is {@code null}.
*/
public static <T extends FieldElement<T>> FieldMatrix<T>
createColumnFieldMatrix(final T[] columnData)
throws NoDataException, NullArgumentException {
if (columnData == null) {
throw new NullArgumentException();
}
final int nRows = columnData.length;
if (nRows == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
}
final FieldMatrix<T> m = createFieldMatrix(columnData[0].getField(), nRows, 1);
for (int i = 0; i < nRows; ++i) {
m.setEntry(i, 0, columnData[i]);
}
return m;
}
/**
* Checks whether a matrix is symmetric, within a given relative tolerance.
*
* @param matrix Matrix to check.
* @param relativeTolerance Tolerance of the symmetry check.
* @param raiseException If {@code true}, an exception will be raised if
* the matrix is not symmetric.
* @return {@code true} if {@code matrix} is symmetric.
* @throws NonSquareMatrixException if the matrix is not square.
* @throws NonSymmetricMatrixException if the matrix is not symmetric.
*/
private static boolean isSymmetricInternal(RealMatrix matrix,
double relativeTolerance,
boolean raiseException) {
final int rows = matrix.getRowDimension();
if (rows != matrix.getColumnDimension()) {
if (raiseException) {
throw new NonSquareMatrixException(rows, matrix.getColumnDimension());
} else {
return false;
}
}
for (int i = 0; i < rows; i++) {
for (int j = i + 1; j < rows; j++) {
final double mij = matrix.getEntry(i, j);
final double mji = matrix.getEntry(j, i);
if (FastMath.abs(mij - mji) >
FastMath.max(FastMath.abs(mij), FastMath.abs(mji)) * relativeTolerance) {
if (raiseException) {
throw new NonSymmetricMatrixException(i, j, relativeTolerance);
} else {
return false;
}
}
}
}
return true;
}
/**
* Checks whether a matrix is symmetric.
*
* @param matrix Matrix to check.
* @param eps Relative tolerance.
* @throws NonSquareMatrixException if the matrix is not square.
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
* @throws NonSymmetricMatrixException if the matrix is not symmetric.
* @since 3.1
*/
public static void checkSymmetric(RealMatrix matrix,
double eps) {
isSymmetricInternal(matrix, eps, true);
}
/**
* Checks whether a matrix is symmetric.
*
* @param matrix Matrix to check.
* @param eps Relative tolerance.
* @return {@code true} if {@code matrix} is symmetric.
* @since 3.1
*/
public static boolean isSymmetric(RealMatrix matrix,
double eps) {
return isSymmetricInternal(matrix, eps, false);
}
/**
* Check if matrix indices are valid.
*
* @param m Matrix.
* @param row Row index to check.
* @param column Column index to check.
* @throws OutOfRangeException if {@code row} or {@code column} is not
* a valid index.
*/
public static void checkMatrixIndex(final AnyMatrix m,
final int row, final int column)
throws OutOfRangeException {
checkRowIndex(m, row);
checkColumnIndex(m, column);
}
/**
* Check if a row index is valid.
*
* @param m Matrix.
* @param row Row index to check.
* @throws OutOfRangeException if {@code row} is not a valid index.
*/
public static void checkRowIndex(final AnyMatrix m, final int row)
throws OutOfRangeException {
if (row < 0 ||
row >= m.getRowDimension()) {
throw new OutOfRangeException(LocalizedFormats.ROW_INDEX,
row, 0, m.getRowDimension() - 1);
}
}
/**
* Check if a column index is valid.
*
* @param m Matrix.
* @param column Column index to check.
* @throws OutOfRangeException if {@code column} is not a valid index.
*/
public static void checkColumnIndex(final AnyMatrix m, final int column)
throws OutOfRangeException {
if (column < 0 || column >= m.getColumnDimension()) {
throw new OutOfRangeException(LocalizedFormats.COLUMN_INDEX,
column, 0, m.getColumnDimension() - 1);
}
}
/**
* Check if submatrix ranges indices are valid.
* Rows and columns are indicated counting from 0 to {@code n - 1}.
*
* @param m Matrix.
* @param startRow Initial row index.
* @param endRow Final row index.
* @param startColumn Initial column index.
* @param endColumn Final column index.
* @throws OutOfRangeException if the indices are invalid.
* @throws NumberIsTooSmallException if {@code endRow < startRow} or
* {@code endColumn < startColumn}.
*/
public static void checkSubMatrixIndex(final AnyMatrix m,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws NumberIsTooSmallException, OutOfRangeException {
checkRowIndex(m, startRow);
checkRowIndex(m, endRow);
if (endRow < startRow) {
throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_ROW_AFTER_FINAL_ROW,
endRow, startRow, false);
}
checkColumnIndex(m, startColumn);
checkColumnIndex(m, endColumn);
if (endColumn < startColumn) {
throw new NumberIsTooSmallException(LocalizedFormats.INITIAL_COLUMN_AFTER_FINAL_COLUMN,
endColumn, startColumn, false);
}
}
/**
* Check if submatrix ranges indices are valid.
*
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> Rows and columns are indicated counting from 0 to n-1.
*
* @param m Matrix.
* @param selectedRows Array of row indices.
* @param selectedColumns Array of column indices.
* @throws NullArgumentException if {@code selectedRows} or
* {@code selectedColumns} are {@code null}.
* @throws NoDataException if the row or column selections are empty (zero
* length).
* @throws OutOfRangeException if row or column selections are not valid.
*/
public static void checkSubMatrixIndex(final AnyMatrix m,
final int[] selectedRows,
final int[] selectedColumns)
throws NoDataException, NullArgumentException, OutOfRangeException {
if (selectedRows == null) {
throw new NullArgumentException();
}
if (selectedColumns == null) {
throw new NullArgumentException();
}
if (selectedRows.length == 0) {
throw new NoDataException(LocalizedFormats.EMPTY_SELECTED_ROW_INDEX_ARRAY);
}
if (selectedColumns.length == 0) {
throw new NoDataException(LocalizedFormats.EMPTY_SELECTED_COLUMN_INDEX_ARRAY);
}
for (final int row : selectedRows) {
checkRowIndex(m, row);
}
for (final int column : selectedColumns) {
checkColumnIndex(m, column);
}
}
/**
* Check if matrices are addition compatible.
*
* @param left Left hand side matrix.
* @param right Right hand side matrix.
* @throws MatrixDimensionMismatchException if the matrices are not addition
* compatible.
*/
public static void checkAdditionCompatible(final AnyMatrix left, final AnyMatrix right)
throws MatrixDimensionMismatchException {
if ((left.getRowDimension() != right.getRowDimension()) ||
(left.getColumnDimension() != right.getColumnDimension())) {
throw new MatrixDimensionMismatchException(left.getRowDimension(), left.getColumnDimension(),
right.getRowDimension(), right.getColumnDimension());
}
}
/**
* Check if matrices are subtraction compatible
*
* @param left Left hand side matrix.
* @param right Right hand side matrix.
* @throws MatrixDimensionMismatchException if the matrices are not addition
* compatible.
*/
public static void checkSubtractionCompatible(final AnyMatrix left, final AnyMatrix right)
throws MatrixDimensionMismatchException {
if ((left.getRowDimension() != right.getRowDimension()) ||
(left.getColumnDimension() != right.getColumnDimension())) {
throw new MatrixDimensionMismatchException(left.getRowDimension(), left.getColumnDimension(),
right.getRowDimension(), right.getColumnDimension());
}
}
/**
* Check if matrices are multiplication compatible
*
* @param left Left hand side matrix.
* @param right Right hand side matrix.
* @throws DimensionMismatchException if matrices are not multiplication
* compatible.
*/
public static void checkMultiplicationCompatible(final AnyMatrix left, final AnyMatrix right)
throws DimensionMismatchException {
if (left.getColumnDimension() != right.getRowDimension()) {
throw new DimensionMismatchException(left.getColumnDimension(),
right.getRowDimension());
}
}
/**
* Convert a {@link FieldMatrix}/{@link Fraction} matrix to a {@link RealMatrix}.
* @param m Matrix to convert.
* @return the converted matrix.
*/
public static Array2DRowRealMatrix fractionMatrixToRealMatrix(final FieldMatrix<Fraction> m) {
final FractionMatrixConverter converter = new FractionMatrixConverter();
m.walkInOptimizedOrder(converter);
return converter.getConvertedMatrix();
}
/** Converter for {@link FieldMatrix}/{@link Fraction}. */
private static class FractionMatrixConverter extends DefaultFieldMatrixPreservingVisitor<Fraction> {
/** Convert
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>>
*
* @param vector real vector to serialize
* @param oos stream where the real vector should be written
* @exception IOException if object cannot be written to stream
* @see #deserializeRealVector(Object, String, ObjectInputStream)
*/
public static void serializeRealVector(final RealVector vector,
final ObjectOutputStream oos)
throws IOException {
final int n = vector.getDimension();
oos.writeInt(n);
for (int i = 0; i < n; ++i) {
oos.writeDouble(vector.getEntry(i));
}
}
/** Deserialize a {@link RealVector} field in a class.
* <p>
* This method is intended to be called from within a private
* <code>readObject</code> method (after a call to
* <code>ois.defaultReadObject()</code>) in a class that has a
* {@link RealVector} field, which should be declared <code>transient</code>.
* This way, the default handling does not deserialize the vector (the {@link
* RealVector} interface is not serializable by default) but this method does
* deserialize it specifically.
* </p>
* @param instance instance in which the field must be set up
* @param fieldName name of the field within the class (may be private and final)
* @param ois stream from which the real vector should be read
* @exception ClassNotFoundException if a class in the stream cannot be found
* @exception IOException if object cannot be read from the stream
* @see #serializeRealVector(RealVector, ObjectOutputStream)
*/
public static void deserializeRealVector(final Object instance,
final String fieldName,
final ObjectInputStream ois)
throws ClassNotFoundException, IOException {
try {
// read the vector data
final int n = ois.readInt();
final double[] data = new double[n];
for (int i = 0; i < n; ++i) {
data[i] = ois.readDouble();
}
// create the instance
final RealVector vector = new ArrayRealVector(data, false);
// set up the field
final java.lang.reflect.Field f =
instance.getClass().getDeclaredField(fieldName);
f.setAccessible(true);
f.set(instance, vector);
} catch (NoSuchFieldException nsfe) {
IOException ioe = new IOException();
ioe.initCause(nsfe);
throw ioe;
} catch (IllegalAccessException iae) {
IOException ioe = new IOException();
ioe.initCause(iae);
throw ioe;
}
}
/** Serialize a {@link RealMatrix}.
* <p>
* This method is intended to be called from within a private
* <code>writeObject</code> method (after a call to
* <code>oos.defaultWriteObject()</code>) in a class that has a
* {@link RealMatrix} field, which should be declared <code>transient</code>.
* This way, the default handling does not serialize the matrix (the {@link
* RealMatrix} interface is not serializable by default) but this method does
* serialize it specifically.
* </p>
* <p>
* The following example shows how a simple class with a name and a real matrix
* should be written:
* <pre><code>
* public class NamedMatrix implements Serializable {
*
* private final String name;
* private final transient RealMatrix coefficients;
*
* // omitted constructors, getters ...
*
* private void writeObject(ObjectOutputStream oos) throws IOException {
* oos.defaultWriteObject(); // takes care of name field
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> * MatrixUtils.serializeRealMatrix(coefficients, oos);
* }
*
* private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
* ois.defaultReadObject(); // takes care of name field
* MatrixUtils.deserializeRealMatrix(this, "coefficients", ois);
* }
*
* }
* </code></pre>
* </p>
*
* @param matrix real matrix to serialize
* @param oos stream where the real matrix should be written
* @exception IOException if object cannot be written to stream
* @see #deserializeRealMatrix(Object, String, ObjectInputStream)
*/
public static void serializeRealMatrix(final RealMatrix matrix,
final ObjectOutputStream oos)
throws IOException {
final int n = matrix.getRowDimension();
final int m = matrix.getColumnDimension();
oos.writeInt(n);
oos.writeInt(m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
oos.writeDouble(matrix.getEntry(i, j));
}
}
}
/** Deserialize a {@link RealMatrix} field in a class.
* <p>
* This method is intended to be called from within a private
* <code>readObject</code> method (after a call to
* <code>ois.defaultReadObject()</code>) in a class that has a
* {@link RealMatrix} field, which should be declared <code>transient</code>.
* This way, the default handling does not deserialize the matrix (the {@link
* RealMatrix} interface is not serializable by default) but this method does
* deserialize it specifically.
* </p>
* @param instance instance in which the field must be set up
* @param fieldName name of the field within the class (may be private and final)
* @param ois stream from which the real matrix should be read
* @exception ClassNotFoundException if a class in the stream cannot be found
* @exception IOException if object cannot be read from the stream
* @see #serializeRealMatrix(RealMatrix, ObjectOutputStream)
*/
public static void deserializeRealMatrix(final Object instance,
final String fieldName,
final ObjectInputStream ois)
throws ClassNotFoundException, IOException {
try {
// read the matrix data
final int n = ois.readInt();
final int m = ois.readInt();
final double[][] data = new double[n][m];
for (int i = 0; i < n; ++i) {
final double[] dataI = data[i];
for (int j = 0; j < m; ++j) {
dataI[j] = ois.readDouble();
}
}
// create the instance
final RealMatrix matrix = new Array2DRowRealMatrix(data, false);
// set up the field
final java.lang.reflect.Field f =
instance.getClass().getDeclaredField(fieldName);
f.setAccessible(true);
f.set(instance, matrix);
} catch (NoSuchFieldException nsfe) {
IOException ioe = new IOException();
ioe.initCause(nsfe);
throw ioe;
} catch (IllegalAccessException iae) {
IOException ioe = new IOException();
ioe.initCause(iae);
throw ioe;
}
}
/**Solve a system of composed of a Lower Triangular Matrix
* {@link RealMatrix}.
* <p>
* This method is called to solve systems of equations which are
* of the lower triangular form. The matrix {@link RealMatrix}
*
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> is assumed, though not checked, to be in lower triangular form.
* The vector {@link RealVector} is overwritten with the solution.
* The matrix is checked that it is square and its dimensions match
* the length of the vector.
* </p>
* @param rm RealMatrix which is lower triangular
* @param b RealVector this is overwritten
* @throws DimensionMismatchException if the matrix and vector are not
* conformable
* @throws NonSquareMatrixException if the matrix {@code rm} is not square
* @throws MathArithmeticException if the absolute value of one of the diagonal
* coefficient of {@code rm} is lower than {@link Precision#SAFE_MIN}
*/
public static void solveLowerTriangularSystem(RealMatrix rm, RealVector b)
throws DimensionMismatchException, MathArithmeticException,
NonSquareMatrixException {
if ((rm == null) || (b == null) || ( rm.getRowDimension() != b.getDimension())) {
throw new DimensionMismatchException(
(rm == null) ? 0 : rm.getRowDimension(),
(b == null) ? 0 : b.getDimension());
}
if( rm.getColumnDimension() != rm.getRowDimension() ){
throw new NonSquareMatrixException(rm.getRowDimension(),
rm.getColumnDimension());
}
int rows = rm.getRowDimension();
for( int i = 0 ; i < rows ; i++ ){
double diag = rm.getEntry(i, i);
if( FastMath.abs(diag) < Precision.SAFE_MIN ){
throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR);
}
double bi = b.getEntry(i)/diag;
b.setEntry(i, bi );
for( int j = i+1; j< rows; j++ ){
b.setEntry(j, b.getEntry(j)-bi*rm.getEntry(j,i) );
}
}
}
/** Solver a system composed of an Upper Triangular Matrix
* {@link RealMatrix}.
* <p>
* This method is called to solve systems of equations which are
* of the lower triangular form. The matrix {@link RealMatrix}
* is assumed, though not checked, to be in upper triangular form.
* The vector {@link RealVector} is overwritten with the solution.
* The matrix is checked that it is square and its dimensions match
* the length of the vector.
* </p>
* @param rm RealMatrix which is upper triangular
* @param b RealVector this is overwritten
* @throws DimensionMismatchException if the matrix and vector are not
* conformable
* @throws NonSquareMatrixException if the matrix {@code rm} is not
* square
* @throws MathArithmeticException if the absolute value of one of the diagonal
* coefficient of {@code rm} is lower than {@link Precision#SAFE_MIN}
*/
public static void solveUpperTriangularSystem(RealMatrix rm, RealVector b)
throws DimensionMismatchException, MathArithmeticException,
NonSquareMatrixException {
if ((rm == null) || (b == null) || ( rm.getRowDimension() != b.getDimension())) {
throw new DimensionMismatchException(
(rm == null) ? 0 : rm.getRowDimension(),
(b == null) ? 0 : b.getDimension());
}
if( rm.getColumnDimension() != rm.getRowDimension() ){
throw new NonSquareMatrixException(rm.getRowDimension(),
rm.getColumnDimension());
}
int rows = rm.getRowDimension();
for( int i = rows-1 ; i >-1 ; i-- ){
double diag = rm.getEntry(i, i);
if( Fast
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Math.abs(diag) < Precision.SAFE_MIN ){
throw new MathArithmeticException(LocalizedFormats.ZERO_DENOMINATOR);
}
double bi = b.getEntry(i)/diag;
b.setEntry(i, bi );
for( int j = i-1; j>-1; j-- ){
b.setEntry(j, b.getEntry(j)-bi*rm.getEntry(j,i) );
}
}
}
/**
* Computes the inverse of the given matrix by splitting it into
* 4 sub-matrices.
*
* @param m Matrix whose inverse must be computed.
* @param splitIndex Index that determines the "split" line and
* column.
* The element corresponding to this index will part of the
* upper-left sub-matrix.
* @return the inverse of {@code m}.
* @throws NonSquareMatrixException if {@code m} is not square.
*/
public static RealMatrix blockInverse(RealMatrix m,
int splitIndex) {
final int n = m.getRowDimension();
if (m.getColumnDimension() != n) {
throw new NonSquareMatrixException(m.getRowDimension(),
m.getColumnDimension());
}
final int splitIndex1 = splitIndex + 1;
final RealMatrix a = m.getSubMatrix(0, splitIndex, 0, splitIndex);
final RealMatrix b = m.getSubMatrix(0, splitIndex, splitIndex1, n - 1);
final RealMatrix c = m.getSubMatrix(splitIndex1, n - 1, 0, splitIndex);
final RealMatrix d = m.getSubMatrix(splitIndex1, n - 1, splitIndex1, n - 1);
final SingularValueDecomposition aDec = new SingularValueDecomposition(a);
final RealMatrix aInv = aDec.getSolver().getInverse();
final SingularValueDecomposition dDec = new SingularValueDecomposition(d);
final RealMatrix dInv = dDec.getSolver().getInverse();
final RealMatrix tmp1 = a.subtract(b.multiply(dInv).multiply(c));
final SingularValueDecomposition tmp1Dec = new SingularValueDecomposition(tmp1);
final RealMatrix result00 = tmp1Dec.getSolver().getInverse();
final RealMatrix tmp2 = d.subtract(c.multiply(aInv).multiply(b));
final SingularValueDecomposition tmp2Dec = new SingularValueDecomposition(tmp2);
final RealMatrix result11 = tmp2Dec.getSolver().getInverse();
final RealMatrix result01 = aInv.multiply(b).multiply(result11).scalarMultiply(-1);
final RealMatrix result10 = dInv.multiply(c).multiply(result00).scalarMultiply(-1);
final RealMatrix result = new Array2DRowRealMatrix(n, n);
result.setSubMatrix(result00.getData(), 0, 0);
result.setSubMatrix(result01.getData(), 0, splitIndex1);
result.setSubMatrix(result10.getData(), splitIndex1, 0);
result.setSubMatrix(result11.getData(), splitIndex1, splitIndex1);
return result;
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> in order to be embedded in a
* RealMatrix and not used directly, the {@code copyArray} may be
* set to {@code false}. This will prevent the copying and improve
* performance as no new array will be built and no data will be copied.
*
* @param d Data for new matrix.
* @param copyArray if {@code true}, the input array will be copied,
* otherwise it will be referenced.
* @throws DimensionMismatchException if {@code d} is not rectangular.
* @throws NoDataException if {@code d} row or colum dimension is zero.
* @throws NullArgumentException if {@code d} is {@code null}.
* @see #Array2DRowRealMatrix(double[][])
*/
public Array2DRowRealMatrix(final double[][] d, final boolean copyArray)
throws DimensionMismatchException, NoDataException,
NullArgumentException {
if (copyArray) {
copyIn(d);
} else {
if (d == null) {
throw new NullArgumentException();
}
final int nRows = d.length;
if (nRows == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
}
final int nCols = d[0].length;
if (nCols == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
for (int r = 1; r < nRows; r++) {
if (d[r].length != nCols) {
throw new DimensionMismatchException(d[r].length, nCols);
}
}
data = d;
}
}
/**
* Create a new (column) RealMatrix using {@code v} as the
* data for the unique column of the created matrix.
* The input array is copied.
*
* @param v Column vector holding data for new matrix.
*/
public Array2DRowRealMatrix(final double[] v) {
final int nRows = v.length;
data = new double[nRows][1];
for (int row = 0; row < nRows; row++) {
data[row][0] = v[row];
}
}
/** {@inheritDoc} */
@Override
public RealMatrix createMatrix(final int rowDimension,
final int columnDimension)
throws NotStrictlyPositiveException {
return new Array2DRowRealMatrix(rowDimension, columnDimension);
}
/** {@inheritDoc} */
@Override
public RealMatrix copy() {
return new Array2DRowRealMatrix(copyOut(), false);
}
/**
* Compute the sum of {@code this} and {@code m}.
*
* @param m Matrix to be added.
* @return {@code this + m}.
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as {@code this}.
*/
public Array2DRowRealMatrix add(final Array2DRowRealMatrix m)
throws MatrixDimensionMismatchException {
// Safety check.
MatrixUtils.checkAdditionCompatible(this, m);
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final double[][] outData = new double[rowCount][columnCount];
for (int row = 0; row < rowCount; row++) {
final double[] dataRow = data[row];
final double[] mRow = m.data[row];
final double[] outDataRow = outData[row];
for (int col = 0; col < columnCount; col++) {
outDataRow[col] = dataRow[col] + mRow[col];
}
}
return new Array
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>2DRowRealMatrix(outData, false);
}
/**
* Returns {@code this} minus {@code m}.
*
* @param m Matrix to be subtracted.
* @return {@code this - m}
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as {@code this}.
*/
public Array2DRowRealMatrix subtract(final Array2DRowRealMatrix m)
throws MatrixDimensionMismatchException {
MatrixUtils.checkSubtractionCompatible(this, m);
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final double[][] outData = new double[rowCount][columnCount];
for (int row = 0; row < rowCount; row++) {
final double[] dataRow = data[row];
final double[] mRow = m.data[row];
final double[] outDataRow = outData[row];
for (int col = 0; col < columnCount; col++) {
outDataRow[col] = dataRow[col] - mRow[col];
}
}
return new Array2DRowRealMatrix(outData, false);
}
/**
* Returns the result of postmultiplying {@code this} by {@code m}.
*
* @param m matrix to postmultiply by
* @return {@code this * m}
* @throws DimensionMismatchException if
* {@code columnDimension(this) != rowDimension(m)}
*/
public Array2DRowRealMatrix multiply(final Array2DRowRealMatrix m)
throws DimensionMismatchException {
MatrixUtils.checkMultiplicationCompatible(this, m);
final int nRows = this.getRowDimension();
final int nCols = m.getColumnDimension();
final int nSum = this.getColumnDimension();
final double[][] outData = new double[nRows][nCols];
// Will hold a column of "m".
final double[] mCol = new double[nSum];
final double[][] mData = m.data;
// Multiply.
for (int col = 0; col < nCols; col++) {
// Copy all elements of column "col" of "m" so that
// will be in contiguous memory.
for (int mRow = 0; mRow < nSum; mRow++) {
mCol[mRow] = mData[mRow][col];
}
for (int row = 0; row < nRows; row++) {
final double[] dataRow = data[row];
double sum = 0;
for (int i = 0; i < nSum; i++) {
sum += dataRow[i] * mCol[i];
}
outData[row][col] = sum;
}
}
return new Array2DRowRealMatrix(outData, false);
}
/** {@inheritDoc} */
@Override
public double[][] getData() {
return copyOut();
}
/**
* Get a reference to the underlying data array.
*
* @return 2-dimensional array of entries.
*/
public double[][] getDataRef() {
return data;
}
/** {@inheritDoc} */
@Override
public void setSubMatrix(final double[][] subMatrix, final int row,
final int column)
throws NoDataException, OutOfRangeException,
DimensionMismatchException, NullArgumentException {
if (data == null) {
if (row > 0) {
throw new MathIllegalStateException(LocalizedFormats.FIRST_ROWS_NOT_INITIALIZED_YET, row);
}
if (column > 0) {
throw new MathIllegalStateException(LocalizedFormats.FIRST_COLUMNS_NOT_INITIALIZED_YET, column);
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> }
MathUtils.checkNotNull(subMatrix);
final int nRows = subMatrix.length;
if (nRows == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
}
final int nCols = subMatrix[0].length;
if (nCols == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
data = new double[subMatrix.length][nCols];
for (int i = 0; i < data.length; ++i) {
if (subMatrix[i].length != nCols) {
throw new DimensionMismatchException(subMatrix[i].length, nCols);
}
System.arraycopy(subMatrix[i], 0, data[i + row], column, nCols);
}
} else {
super.setSubMatrix(subMatrix, row, column);
}
}
/** {@inheritDoc} */
@Override
public double getEntry(final int row, final int column)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
return data[row][column];
}
/** {@inheritDoc} */
@Override
public void setEntry(final int row, final int column, final double value)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
data[row][column] = value;
}
/** {@inheritDoc} */
@Override
public void addToEntry(final int row, final int column,
final double increment)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
data[row][column] += increment;
}
/** {@inheritDoc} */
@Override
public void multiplyEntry(final int row, final int column,
final double factor)
throws OutOfRangeException {
MatrixUtils.checkMatrixIndex(this, row, column);
data[row][column] *= factor;
}
/** {@inheritDoc} */
@Override
public int getRowDimension() {
return (data == null) ? 0 : data.length;
}
/** {@inheritDoc} */
@Override
public int getColumnDimension() {
return ((data == null) || (data[0] == null)) ? 0 : data[0].length;
}
/** {@inheritDoc} */
@Override
public double[] operate(final double[] v)
throws DimensionMismatchException {
final int nRows = this.getRowDimension();
final int nCols = this.getColumnDimension();
if (v.length != nCols) {
throw new DimensionMismatchException(v.length, nCols);
}
final double[] out = new double[nRows];
for (int row = 0; row < nRows; row++) {
final double[] dataRow = data[row];
double sum = 0;
for (int i = 0; i < nCols; i++) {
sum += dataRow[i] * v[i];
}
out[row] = sum;
}
return out;
}
/** {@inheritDoc} */
@Override
public double[] preMultiply(final double[] v)
throws DimensionMismatchException {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.length != nRows) {
throw new DimensionMismatchException(v.length, nRows);
}
final double[] out = new double[nCols];
for (int col = 0; col < nCols; ++col) {
double sum = 0;
for (int i = 0; i < nRows; ++i) {
sum
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> += data[i][col] * v[i];
}
out[col] = sum;
}
return out;
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixChangingVisitor visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int i = 0; i < rows; ++i) {
final double[] rowI = data[i];
for (int j = 0; j < columns; ++j) {
rowI[j] = visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int i = 0; i < rows; ++i) {
final double[] rowI = data[i];
for (int j = 0; j < columns; ++j) {
visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int i = startRow; i <= endRow; ++i) {
final double[] rowI = data[i];
for (int j = startColumn; j <= endColumn; ++j) {
rowI[j] = visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInRowOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int i = startRow; i <= endRow; ++i) {
final double[] rowI = data[i];
for (int j = startColumn; j <= endColumn; ++j) {
visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInColumnOrder(final RealMatrixChangingVisitor visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int j = 0; j < columns; ++j) {
for (int i = 0; i < rows; ++i) {
final double[] rowI = data[i];
rowI[j] = visitor.visit(i, j, rowI[j]);
}
}
return
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInColumnOrder(final RealMatrixPreservingVisitor visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int j = 0; j < columns; ++j) {
for (int i = 0; i < rows; ++i) {
visitor.visit(i, j, data[i][j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInColumnOrder(final RealMatrixChangingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int j = startColumn; j <= endColumn; ++j) {
for (int i = startRow; i <= endRow; ++i) {
final double[] rowI = data[i];
rowI[j] = visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public double walkInColumnOrder(final RealMatrixPreservingVisitor visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
MatrixUtils.checkSubMatrixIndex(this, startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int j = startColumn; j <= endColumn; ++j) {
for (int i = startRow; i <= endRow; ++i) {
visitor.visit(i, j, data[i][j]);
}
}
return visitor.end();
}
/**
* Get a fresh copy of the underlying data array.
*
* @return a copy of the underlying data array.
*/
private double[][] copyOut() {
final int nRows = this.getRowDimension();
final double[][] out = new double[nRows][this.getColumnDimension()];
// can't copy 2-d array in one shot, otherwise get row references
for (int i = 0; i < nRows; i++) {
System.arraycopy(data[i], 0, out[i], 0, data[i].length);
}
return out;
}
/**
* Replace data with a fresh copy of the input array.
*
* @param in Data to copy.
* @throws NoDataException if the input array is empty.
* @throws DimensionMismatchException if the input array is not rectangular.
* @throws NullArgumentException if the input array is {@code null}.
*/
private void copyIn(final double[][] in)
throws DimensionMismatchException, NoDataException, NullArgumentException {
setSubMatrix(in, 0, 0);
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> {@code true} if the values are equal or within range of each other.
* @since 2.2
*/
public static boolean equals(float x, float y, float eps) {
return equals(x, y, 1) || FastMath.abs(y - x) <= eps;
}
/**
* Returns true if both arguments are NaN or are equal or within the range
* of allowed error (inclusive).
*
* @param x first value
* @param y second value
* @param eps the amount of absolute error to allow.
* @return {@code true} if the values are equal or within range of each other,
* or both are NaN.
* @since 2.2
*/
public static boolean equalsIncludingNaN(float x, float y, float eps) {
return equalsIncludingNaN(x, y) || (FastMath.abs(y - x) <= eps);
}
/**
* Returns true if both arguments are equal or within the range of allowed
* error (inclusive).
* Two float numbers are considered equal if there are {@code (maxUlps - 1)}
* (or fewer) floating point numbers between them, i.e. two adjacent floating
* point numbers are considered equal.
* Adapted from <a
* href="http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm">
* Bruce Dawson</a>
*
* @param x first value
* @param y second value
* @param maxUlps {@code (maxUlps - 1)} is the number of floating point
* values between {@code x} and {@code y}.
* @return {@code true} if there are fewer than {@code maxUlps} floating
* point values between {@code x} and {@code y}.
* @since 2.2
*/
public static boolean equals(float x, float y, int maxUlps) {
int xInt = Float.floatToIntBits(x);
int yInt = Float.floatToIntBits(y);
// Make lexicographically ordered as a two's-complement integer.
if (xInt < 0) {
xInt = SGN_MASK_FLOAT - xInt;
}
if (yInt < 0) {
yInt = SGN_MASK_FLOAT - yInt;
}
final boolean isEqual = FastMath.abs(xInt - yInt) <= maxUlps;
return isEqual && !Float.isNaN(x) && !Float.isNaN(y);
}
/**
* Returns true if both arguments are NaN or if they are equal as defined
* by {@link #equals(float,float,int) equals(x, y, maxUlps)}.
*
* @param x first value
* @param y second value
* @param maxUlps {@code (maxUlps - 1)} is the number of floating point
* values between {@code x} and {@code y}.
* @return {@code true} if both arguments are NaN or if there are less than
* {@code maxUlps} floating point values between {@code x} and {@code y}.
* @since 2.2
*/
public static boolean equalsIncludingNaN(float x, float y, int maxUlps) {
return (Float.isNaN(x) && Float.isNaN(y)) || equals(x, y, maxUlps);
}
/**
* Returns true iff they are equal as defined by
* {@link #equals(double,double,int) equals(x, y, 1)}.
*
* @param x first value
* @param y second value
*
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> @return {@code true} if the values are equal.
*/
public static boolean equals(double x, double y) {
return equals(x, y, 1);
}
/**
* Returns true if both arguments are NaN or neither is NaN and they are
* equal as defined by {@link #equals(double,double) equals(x, y, 1)}.
*
* @param x first value
* @param y second value
* @return {@code true} if the values are equal or both are NaN.
* @since 2.2
*/
public static boolean equalsIncludingNaN(double x, double y) {
return (Double.isNaN(x) && Double.isNaN(y)) || equals(x, y, 1);
}
/**
* Returns {@code true} if there is no double value strictly between the
* arguments or the difference between them is within the range of allowed
* error (inclusive).
*
* @param x First value.
* @param y Second value.
* @param eps Amount of allowed absolute error.
* @return {@code true} if the values are two adjacent floating point
* numbers or they are within range of each other.
*/
public static boolean equals(double x, double y, double eps) {
return equals(x, y, 1) || FastMath.abs(y - x) <= eps;
}
/**
* Returns {@code true} if there is no double value strictly between the
* arguments or the reltaive difference between them is smaller or equal
* to the given tolerance.
*
* @param x First value.
* @param y Second value.
* @param eps Amount of allowed relative error.
* @return {@code true} if the values are two adjacent floating point
* numbers or they are within range of each other.
* @since 3.1
*/
public static boolean equalsWithRelativeTolerance(double x, double y, double eps) {
if (equals(x, y, 1)) {
return true;
}
final double absoluteMax = FastMath.max(FastMath.abs(x), FastMath.abs(y));
final double relativeDifference = FastMath.abs((x - y) / absoluteMax);
return relativeDifference <= eps;
}
/**
* Returns true if both arguments are NaN or are equal or within the range
* of allowed error (inclusive).
*
* @param x first value
* @param y second value
* @param eps the amount of absolute error to allow.
* @return {@code true} if the values are equal or within range of each other,
* or both are NaN.
* @since 2.2
*/
public static boolean equalsIncludingNaN(double x, double y, double eps) {
return equalsIncludingNaN(x, y) || (FastMath.abs(y - x) <= eps);
}
/**
* Returns true if both arguments are equal or within the range of allowed
* error (inclusive).
* Two float numbers are considered equal if there are {@code (maxUlps - 1)}
* (or fewer) floating point numbers between them, i.e. two adjacent floating
* point numbers are considered equal.
* Adapted from <a
* href="http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm">
* Bruce Dawson</a>
*
* @param x first value
* @param y second value
* @param maxUlps {@code (maxUlps - 1)} is the number of floating point
* values between {@code x} and {@code y}.
* @return {@code true}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> if there are fewer than {@code maxUlps} floating
* point values between {@code x} and {@code y}.
*/
public static boolean equals(double x, double y, int maxUlps) {
long xInt = Double.doubleToLongBits(x);
long yInt = Double.doubleToLongBits(y);
// Make lexicographically ordered as a two's-complement integer.
if (xInt < 0) {
xInt = SGN_MASK - xInt;
}
if (yInt < 0) {
yInt = SGN_MASK - yInt;
}
final boolean isEqual = FastMath.abs(xInt - yInt) <= maxUlps;
return isEqual && !Double.isNaN(x) && !Double.isNaN(y);
}
/**
* Returns true if both arguments are NaN or if they are equal as defined
* by {@link #equals(double,double,int) equals(x, y, maxUlps)}.
*
* @param x first value
* @param y second value
* @param maxUlps {@code (maxUlps - 1)} is the number of floating point
* values between {@code x} and {@code y}.
* @return {@code true} if both arguments are NaN or if there are less than
* {@code maxUlps} floating point values between {@code x} and {@code y}.
* @since 2.2
*/
public static boolean equalsIncludingNaN(double x, double y, int maxUlps) {
return (Double.isNaN(x) && Double.isNaN(y)) || equals(x, y, maxUlps);
}
/**
* Rounds the given value to the specified number of decimal places.
* The value is rounded using the {@link BigDecimal#ROUND_HALF_UP} method.
*
* @param x Value to round.
* @param scale Number of digits to the right of the decimal point.
* @return the rounded value.
* @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
*/
public static double round(double x, int scale) {
return round(x, scale, BigDecimal.ROUND_HALF_UP);
}
/**
* Rounds the given value to the specified number of decimal places.
* The value is rounded using the given method which is any method defined
* in {@link BigDecimal}.
* If {@code x} is infinite or {@code NaN}, then the value of {@code x} is
* returned unchanged, regardless of the other parameters.
*
* @param x Value to round.
* @param scale Number of digits to the right of the decimal point.
* @param roundingMethod Rounding method as defined in {@link BigDecimal}.
* @return the rounded value.
* @throws ArithmeticException if {@code roundingMethod == ROUND_UNNECESSARY}
* and the specified scaling operation would require rounding.
* @throws IllegalArgumentException if {@code roundingMethod} does not
* represent a valid rounding mode.
* @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
*/
public static double round(double x, int scale, int roundingMethod) {
try {
return (new BigDecimal
(Double.toString(x))
.setScale(scale, roundingMethod))
.doubleValue();
} catch (NumberFormatException ex) {
if (Double.isInfinite(x)) {
return x;
} else {
return Double.NaN;
}
}
}
/**
* Rounds the given value to the specified number of decimal places.
* The value is rounded using the
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> {@link BigDecimal#ROUND_HALF_UP} method.
*
* @param x Value to round.
* @param scale Number of digits to the right of the decimal point.
* @return the rounded value.
* @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
*/
public static float round(float x, int scale) {
return round(x, scale, BigDecimal.ROUND_HALF_UP);
}
/**
* Rounds the given value to the specified number of decimal places.
* The value is rounded using the given method which is any method defined
* in {@link BigDecimal}.
*
* @param x Value to round.
* @param scale Number of digits to the right of the decimal point.
* @param roundingMethod Rounding method as defined in {@link BigDecimal}.
* @return the rounded value.
* @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
* @throws MathArithmeticException if an exact operation is required but result is not exact
* @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method.
*/
public static float round(float x, int scale, int roundingMethod)
throws MathArithmeticException, MathIllegalArgumentException {
final float sign = FastMath.copySign(1f, x);
final float factor = (float) FastMath.pow(10.0f, scale) * sign;
return (float) roundUnscaled(x * factor, sign, roundingMethod) / factor;
}
/**
* Rounds the given non-negative value to the "nearest" integer. Nearest is
* determined by the rounding method specified. Rounding methods are defined
* in {@link BigDecimal}.
*
* @param unscaled Value to round.
* @param sign Sign of the original, scaled value.
* @param roundingMethod Rounding method, as defined in {@link BigDecimal}.
* @return the rounded value.
* @throws MathArithmeticException if an exact operation is required but result is not exact
* @throws MathIllegalArgumentException if {@code roundingMethod} is not a valid rounding method.
* @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
*/
private static double roundUnscaled(double unscaled,
double sign,
int roundingMethod)
throws MathArithmeticException, MathIllegalArgumentException {
switch (roundingMethod) {
case BigDecimal.ROUND_CEILING :
if (sign == -1) {
unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
} else {
unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
}
break;
case BigDecimal.ROUND_DOWN :
unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
break;
case BigDecimal.ROUND_FLOOR :
if (sign == -1) {
unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
} else {
unscaled = FastMath.floor(FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY));
}
break;
case BigDecimal.ROUND_HALF_DOWN : {
unscaled = FastMath.nextAfter(unscaled, Double.NEGATIVE_INFINITY);
double fraction = unscaled - FastMath.floor(unscaled);
if (fraction > 0.5) {
unscaled = FastMath.ceil(unscaled);
} else {
unscaled = FastMath.floor(unscaled);
}
break;
}
case BigDecimal
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>.ROUND_HALF_EVEN : {
double fraction = unscaled - FastMath.floor(unscaled);
if (fraction > 0.5) {
unscaled = FastMath.ceil(unscaled);
} else if (fraction < 0.5) {
unscaled = FastMath.floor(unscaled);
} else {
// The following equality test is intentional and needed for rounding purposes
if (FastMath.floor(unscaled) / 2.0 == FastMath.floor(Math
.floor(unscaled) / 2.0)) { // even
unscaled = FastMath.floor(unscaled);
} else { // odd
unscaled = FastMath.ceil(unscaled);
}
}
break;
}
case BigDecimal.ROUND_HALF_UP : {
unscaled = FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY);
double fraction = unscaled - FastMath.floor(unscaled);
if (fraction >= 0.5) {
unscaled = FastMath.ceil(unscaled);
} else {
unscaled = FastMath.floor(unscaled);
}
break;
}
case BigDecimal.ROUND_UNNECESSARY :
if (unscaled != FastMath.floor(unscaled)) {
throw new MathArithmeticException();
}
break;
case BigDecimal.ROUND_UP :
unscaled = FastMath.ceil(FastMath.nextAfter(unscaled, Double.POSITIVE_INFINITY));
break;
default :
throw new MathIllegalArgumentException(LocalizedFormats.INVALID_ROUNDING_METHOD,
roundingMethod,
"ROUND_CEILING", BigDecimal.ROUND_CEILING,
"ROUND_DOWN", BigDecimal.ROUND_DOWN,
"ROUND_FLOOR", BigDecimal.ROUND_FLOOR,
"ROUND_HALF_DOWN", BigDecimal.ROUND_HALF_DOWN,
"ROUND_HALF_EVEN", BigDecimal.ROUND_HALF_EVEN,
"ROUND_HALF_UP", BigDecimal.ROUND_HALF_UP,
"ROUND_UNNECESSARY", BigDecimal.ROUND_UNNECESSARY,
"ROUND_UP", BigDecimal.ROUND_UP);
}
return unscaled;
}
/**
* Computes a number {@code delta} close to {@code originalDelta} with
* the property that <pre><code>
* x + delta - x
* </code></pre>
* is exactly machine-representable.
* This is useful when computing numerical derivatives, in order to reduce
* roundoff errors.
*
* @param x Value.
* @param originalDelta Offset value.
* @return a number {@code delta} so that {@code x + delta} and {@code x}
* differ by a representable floating number.
*/
public static double representableDelta(double x,
double originalDelta) {
return x + originalDelta - x;
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> */
FieldVector<T> mapInvToSelf() throws MathArithmeticException;
/**
* Element-by-element multiplication.
* @param v vector by which instance elements must be multiplied
* @return a vector containing {@code this[i] * v[i]} for all {@code i}
* @throws DimensionMismatchException if {@code v} is not the same size as {@code this}
*/
FieldVector<T> ebeMultiply(FieldVector<T> v)
throws DimensionMismatchException;
/**
* Element-by-element division.
* @param v vector by which instance elements must be divided
* @return a vector containing {@code this[i] / v[i]} for all {@code i}
* @throws DimensionMismatchException if {@code v} is not the same size as {@code this}
* @throws MathArithmeticException if one entry of {@code v} is zero.
*/
FieldVector<T> ebeDivide(FieldVector<T> v)
throws DimensionMismatchException, MathArithmeticException;
/**
* Returns vector entries as a T array.
* @return T array of entries
* @deprecated as of 3.1, to be removed in 4.0. Please use the {@link #toArray()} method instead.
*/
@Deprecated
T[] getData();
/**
* Compute the dot product.
* @param v vector with which dot product should be computed
* @return the scalar dot product of {@code this} and {@code v}
* @throws DimensionMismatchException if {@code v} is not the same size as {@code this}
*/
T dotProduct(FieldVector<T> v) throws DimensionMismatchException;
/**
* Find the orthogonal projection of this vector onto another vector.
* @param v vector onto which {@code this} must be projected
* @return projection of {@code this} onto {@code v}
* @throws DimensionMismatchException if {@code v} is not the same size as {@code this}
* @throws MathArithmeticException if {@code v} is the null vector.
*/
FieldVector<T> projection(FieldVector<T> v)
throws DimensionMismatchException, MathArithmeticException;
/**
* Compute the outer product.
* @param v vector with which outer product should be computed
* @return the matrix outer product between instance and v
*/
FieldMatrix<T> outerProduct(FieldVector<T> v);
/**
* Returns the entry in the specified index.
*
* @param index Index location of entry to be fetched.
* @return the vector entry at {@code index}.
* @throws OutOfRangeException if the index is not valid.
* @see #setEntry(int, FieldElement)
*/
T getEntry(int index) throws OutOfRangeException;
/**
* Set a single element.
* @param index element index.
* @param value new value for the element.
* @throws OutOfRangeException if the index is not valid.
* @see #getEntry(int)
*/
void setEntry(int index, T value) throws OutOfRangeException;
/**
* Returns the size of the vector.
* @return size
*/
int getDimension();
/**
* Construct a vector by appending a vector to this vector.
* @param v vector to append to this one.
* @return a new vector
*/
FieldVector<T> append(FieldVector<T> v);
/**
* Construct a vector by appending a T to this vector.
* @param d T to append.
* @return a new vector
*/
FieldVector<T> append(T d);
/**
* Get a subvector from consecutive elements.
*
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>;
if (length != columns) {
throw new DimensionMismatchException(columns, length);
}
}
// convert array
final Field<T> field = extractField(rawData);
final T[][] blocks = buildArray(field, blockRows * blockColumns, -1);
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
final int iHeight = pEnd - pStart;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final int jWidth = qEnd - qStart;
// allocate new block
final T[] block = buildArray(field, iHeight * jWidth);
blocks[blockIndex] = block;
// copy data
int index = 0;
for (int p = pStart; p < pEnd; ++p) {
System.arraycopy(rawData[p], qStart, block, index, jWidth);
index += jWidth;
}
++blockIndex;
}
}
return blocks;
}
/**
* Create a data array in blocks layout.
* <p>
* This method can be used to create the array argument of the {@link
* #BlockFieldMatrix(int, int, FieldElement[][], boolean)}
* constructor.
* </p>
* @param <T> Type of the field elements.
* @param field Field to which the elements belong.
* @param rows Number of rows in the new matrix.
* @param columns Number of columns in the new matrix.
* @return a new data array in blocks layout.
* @see #toBlocksLayout(FieldElement[][])
* @see #BlockFieldMatrix(int, int, FieldElement[][], boolean)
*/
public static <T extends FieldElement<T>> T[][] createBlocksLayout(final Field<T> field,
final int rows, final int columns) {
final int blockRows = (rows + BLOCK_SIZE - 1) / BLOCK_SIZE;
final int blockColumns = (columns + BLOCK_SIZE - 1) / BLOCK_SIZE;
final T[][] blocks = buildArray(field, blockRows * blockColumns, -1);
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
final int iHeight = pEnd - pStart;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final int jWidth = qEnd - qStart;
blocks[blockIndex] = buildArray(field, iHeight * jWidth);
++blockIndex;
}
}
return blocks;
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> createMatrix(final int rowDimension,
final int columnDimension)
throws NotStrictlyPositiveException {
return new BlockFieldMatrix<T>(getField(), rowDimension,
columnDimension);
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> copy() {
// create an empty matrix
Block
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>FieldMatrix<T> copied = new BlockFieldMatrix<T>(getField(), rows, columns);
// copy the blocks
for (int i = 0; i < blocks.length; ++i) {
System.arraycopy(blocks[i], 0, copied.blocks[i], 0, blocks[i].length);
}
return copied;
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> add(final FieldMatrix<T> m)
throws MatrixDimensionMismatchException {
try {
return add((BlockFieldMatrix<T>) m);
} catch (ClassCastException cce) {
// safety check
checkAdditionCompatible(m);
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), rows, columns);
// perform addition block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
// perform addition on the current block
final T[] outBlock = out.blocks[blockIndex];
final T[] tBlock = blocks[blockIndex];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q) {
outBlock[k] = tBlock[k].add(m.getEntry(p, q));
++k;
}
}
// go to next block
++blockIndex;
}
}
return out;
}
}
/**
* Compute the sum of {@code this} and {@code m}.
*
* @param m matrix to be added
* @return {@code this + m}
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as {@code this}
*/
public BlockFieldMatrix<T> add(final BlockFieldMatrix<T> m)
throws MatrixDimensionMismatchException {
// safety check
checkAdditionCompatible(m);
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), rows, columns);
// perform addition block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final T[] outBlock = out.blocks[blockIndex];
final T[] tBlock = blocks[blockIndex];
final T[] mBlock = m.blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k].add(mBlock[k]);
}
}
return out;
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> subtract(final FieldMatrix<T> m)
throws MatrixDimensionMismatchException {
try {
return subtract((BlockFieldMatrix<T>) m);
} catch (ClassCastException cce) {
// safety check
checkSubtractionCompatible(m);
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock <
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> out.blockRows; ++iBlock) {
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
// perform subtraction on the current block
final T[] outBlock = out.blocks[blockIndex];
final T[] tBlock = blocks[blockIndex];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q) {
outBlock[k] = tBlock[k].subtract(m.getEntry(p, q));
++k;
}
}
// go to next block
++blockIndex;
}
}
return out;
}
}
/**
* Compute {@code this - m}.
*
* @param m matrix to be subtracted
* @return {@code this - m}
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as {@code this}
*/
public BlockFieldMatrix<T> subtract(final BlockFieldMatrix<T> m) throws MatrixDimensionMismatchException {
// safety check
checkSubtractionCompatible(m);
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final T[] outBlock = out.blocks[blockIndex];
final T[] tBlock = blocks[blockIndex];
final T[] mBlock = m.blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k].subtract(mBlock[k]);
}
}
return out;
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> scalarAdd(final T d) {
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final T[] outBlock = out.blocks[blockIndex];
final T[] tBlock = blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k].add(d);
}
}
return out;
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> scalarMultiply(final T d) {
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), rows, columns);
// perform subtraction block-wise, to ensure good cache behavior
for (int blockIndex = 0; blockIndex < out.blocks.length; ++blockIndex) {
final T[] outBlock = out.blocks[blockIndex];
final T[] tBlock = blocks[blockIndex];
for (int k = 0; k < outBlock.length; ++k) {
outBlock[k] = tBlock[k].multiply(d);
}
}
return out;
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> multiply(final Field
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Matrix<T> m)
throws DimensionMismatchException {
try {
return multiply((BlockFieldMatrix<T>) m);
} catch (ClassCastException cce) {
// safety check
checkMultiplicationCompatible(m);
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), rows, m.getColumnDimension());
final T zero = getField().getZero();
// perform multiplication block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, m.getColumnDimension());
// select current block
final T[] outBlock = out.blocks[blockIndex];
// perform multiplication on current block
for (int kBlock = 0; kBlock < blockColumns; ++kBlock) {
final int kWidth = blockWidth(kBlock);
final T[] tBlock = blocks[iBlock * blockColumns + kBlock];
final int rStart = kBlock * BLOCK_SIZE;
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
final int lStart = (p - pStart) * kWidth;
final int lEnd = lStart + kWidth;
for (int q = qStart; q < qEnd; ++q) {
T sum = zero;
int r = rStart;
for (int l = lStart; l < lEnd; ++l) {
sum = sum.add(tBlock[l].multiply(m.getEntry(r, q)));
++r;
}
outBlock[k] = outBlock[k].add(sum);
++k;
}
}
}
// go to next block
++blockIndex;
}
}
return out;
}
}
/**
* Returns the result of postmultiplying {@code this} by {@code m}.
*
* @param m matrix to postmultiply by
* @return {@code this * m}
* @throws DimensionMismatchException if the matrices are not compatible.
*/
public BlockFieldMatrix<T> multiply(BlockFieldMatrix<T> m)
throws DimensionMismatchException {
// safety check
checkMultiplicationCompatible(m);
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), rows, m.columns);
final T zero = getField().getZero();
// perform multiplication block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < out.blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < out.blockColumns; ++jBlock) {
final int jWidth = out.blockWidth(jBlock);
final int jWidth2 = jWidth + jWidth;
final int jWidth3 = jWidth2 + jWidth;
final int jWidth4 = jWidth3 + jWidth;
// select current block
final T[] outBlock = out.blocks[blockIndex];
// perform multiplication on current block
for (int kBlock = 0; kBlock < blockColumns
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>; ++kBlock) {
final int kWidth = blockWidth(kBlock);
final T[] tBlock = blocks[iBlock * blockColumns + kBlock];
final T[] mBlock = m.blocks[kBlock * m.blockColumns + jBlock];
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
final int lStart = (p - pStart) * kWidth;
final int lEnd = lStart + kWidth;
for (int nStart = 0; nStart < jWidth; ++nStart) {
T sum = zero;
int l = lStart;
int n = nStart;
while (l < lEnd - 3) {
sum = sum.
add(tBlock[l].multiply(mBlock[n])).
add(tBlock[l + 1].multiply(mBlock[n + jWidth])).
add(tBlock[l + 2].multiply(mBlock[n + jWidth2])).
add(tBlock[l + 3].multiply(mBlock[n + jWidth3]));
l += 4;
n += jWidth4;
}
while (l < lEnd) {
sum = sum.add(tBlock[l++].multiply(mBlock[n]));
n += jWidth;
}
outBlock[k] = outBlock[k].add(sum);
++k;
}
}
}
// go to next block
++blockIndex;
}
}
return out;
}
/** {@inheritDoc} */
@Override
public T[][] getData() {
final T[][] data = buildArray(getField(), getRowDimension(), getColumnDimension());
final int lastColumns = columns - (blockColumns - 1) * BLOCK_SIZE;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
int regularPos = 0;
int lastPos = 0;
for (int p = pStart; p < pEnd; ++p) {
final T[] dataP = data[p];
int blockIndex = iBlock * blockColumns;
int dataPos = 0;
for (int jBlock = 0; jBlock < blockColumns - 1; ++jBlock) {
System.arraycopy(blocks[blockIndex++], regularPos, dataP, dataPos, BLOCK_SIZE);
dataPos += BLOCK_SIZE;
}
System.arraycopy(blocks[blockIndex], lastPos, dataP, dataPos, lastColumns);
regularPos += BLOCK_SIZE;
lastPos += lastColumns;
}
}
return data;
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> getSubMatrix(final int startRow, final int endRow,
final int startColumn,
final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
// safety checks
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
// create the output matrix
final BlockFieldMatrix<T> out =
new BlockFieldMatrix<T>(getField(), endRow - startRow + 1, endColumn - startColumn + 1);
// compute blocks shifts
final int blockStartRow = startRow / BLOCK_SIZE;
final int rowsShift = startRow % BLOCK_SIZE;
final int blockStartColumn = startColumn / BLOCK_SIZE;
final int columnsShift = startColumn % BLOCK_SIZE;
// perform extraction block-
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>This method can be called only when the specified part fits in both
* blocks, no verification is done here.</p>
* @param srcBlock source block
* @param srcWidth source block width ({@link #BLOCK_SIZE} or smaller)
* @param srcStartRow start row in the source block
* @param srcEndRow end row (exclusive) in the source block
* @param srcStartColumn start column in the source block
* @param srcEndColumn end column (exclusive) in the source block
* @param dstBlock destination block
* @param dstWidth destination block width ({@link #BLOCK_SIZE} or smaller)
* @param dstStartRow start row in the destination block
* @param dstStartColumn start column in the destination block
*/
private void copyBlockPart(final T[] srcBlock, final int srcWidth,
final int srcStartRow, final int srcEndRow,
final int srcStartColumn, final int srcEndColumn,
final T[] dstBlock, final int dstWidth,
final int dstStartRow, final int dstStartColumn) {
final int length = srcEndColumn - srcStartColumn;
int srcPos = srcStartRow * srcWidth + srcStartColumn;
int dstPos = dstStartRow * dstWidth + dstStartColumn;
for (int srcRow = srcStartRow; srcRow < srcEndRow; ++srcRow) {
System.arraycopy(srcBlock, srcPos, dstBlock, dstPos, length);
srcPos += srcWidth;
dstPos += dstWidth;
}
}
/** {@inheritDoc} */
@Override
public void setSubMatrix(final T[][] subMatrix, final int row,
final int column)
throws DimensionMismatchException, OutOfRangeException,
NoDataException, NullArgumentException {
// safety checks
MathUtils.checkNotNull(subMatrix);
final int refLength = subMatrix[0].length;
if (refLength == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
final int endRow = row + subMatrix.length - 1;
final int endColumn = column + refLength - 1;
checkSubMatrixIndex(row, endRow, column, endColumn);
for (final T[] subRow : subMatrix) {
if (subRow.length != refLength) {
throw new DimensionMismatchException(refLength, subRow.length);
}
}
// compute blocks bounds
final int blockStartRow = row / BLOCK_SIZE;
final int blockEndRow = (endRow + BLOCK_SIZE) / BLOCK_SIZE;
final int blockStartColumn = column / BLOCK_SIZE;
final int blockEndColumn = (endColumn + BLOCK_SIZE) / BLOCK_SIZE;
// perform copy block-wise, to ensure good cache behavior
for (int iBlock = blockStartRow; iBlock < blockEndRow; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final int firstRow = iBlock * BLOCK_SIZE;
final int iStart = FastMath.max(row, firstRow);
final int iEnd = FastMath.min(endRow + 1, firstRow + iHeight);
for (int jBlock = blockStartColumn; jBlock < blockEndColumn; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int firstColumn = jBlock * BLOCK_SIZE;
final int jStart = FastMath.max(column, firstColumn);
final int jEnd = FastMath.min(endColumn + 1, firstColumn + jWidth);
final int jLength = jEnd - jStart;
// handle one
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> block, row by row
final T[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = iStart; i < iEnd; ++i) {
System.arraycopy(subMatrix[i - row], jStart - column,
block, (i - firstRow) * jWidth + (jStart - firstColumn),
jLength);
}
}
}
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> getRowMatrix(final int row)
throws OutOfRangeException {
checkRowIndex(row);
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), 1, columns);
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int outBlockIndex = 0;
int outIndex = 0;
T[] outBlock = out.blocks[outBlockIndex];
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final T[] block = blocks[iBlock * blockColumns + jBlock];
final int available = outBlock.length - outIndex;
if (jWidth > available) {
System.arraycopy(block, iRow * jWidth, outBlock, outIndex, available);
outBlock = out.blocks[++outBlockIndex];
System.arraycopy(block, iRow * jWidth, outBlock, 0, jWidth - available);
outIndex = jWidth - available;
} else {
System.arraycopy(block, iRow * jWidth, outBlock, outIndex, jWidth);
outIndex += jWidth;
}
}
return out;
}
/** {@inheritDoc} */
@Override
public void setRowMatrix(final int row, final FieldMatrix<T> matrix)
throws MatrixDimensionMismatchException, OutOfRangeException {
try {
setRowMatrix(row, (BlockFieldMatrix<T>) matrix);
} catch (ClassCastException cce) {
super.setRowMatrix(row, matrix);
}
}
/**
* Sets the entries in row number <code>row</code>
* as a row matrix. Row indices start at 0.
*
* @param row the row to be set
* @param matrix row matrix (must have one row and the same number of columns
* as the instance)
* @throws MatrixDimensionMismatchException if the matrix dimensions do
* not match one instance row.
* @throws OutOfRangeException if the specified row index is invalid.
*/
public void setRowMatrix(final int row, final BlockFieldMatrix<T> matrix)
throws MatrixDimensionMismatchException, OutOfRangeException {
checkRowIndex(row);
final int nCols = getColumnDimension();
if ((matrix.getRowDimension() != 1) ||
(matrix.getColumnDimension() != nCols)) {
throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
matrix.getColumnDimension(),
1, nCols);
}
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int mBlockIndex = 0;
int mIndex = 0;
T[] mBlock = matrix.blocks[mBlockIndex];
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final T[] block = blocks[iBlock * blockColumns + jBlock];
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>
final int available = mBlock.length - mIndex;
if (jWidth > available) {
System.arraycopy(mBlock, mIndex, block, iRow * jWidth, available);
mBlock = matrix.blocks[++mBlockIndex];
System.arraycopy(mBlock, 0, block, iRow * jWidth, jWidth - available);
mIndex = jWidth - available;
} else {
System.arraycopy(mBlock, mIndex, block, iRow * jWidth, jWidth);
mIndex += jWidth;
}
}
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> getColumnMatrix(final int column)
throws OutOfRangeException {
checkColumnIndex(column);
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), rows, 1);
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outBlockIndex = 0;
int outIndex = 0;
T[] outBlock = out.blocks[outBlockIndex];
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final T[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
if (outIndex >= outBlock.length) {
outBlock = out.blocks[++outBlockIndex];
outIndex = 0;
}
outBlock[outIndex++] = block[i * jWidth + jColumn];
}
}
return out;
}
/** {@inheritDoc} */
@Override
public void setColumnMatrix(final int column, final FieldMatrix<T> matrix)
throws MatrixDimensionMismatchException, OutOfRangeException {
try {
setColumnMatrix(column, (BlockFieldMatrix<T>) matrix);
} catch (ClassCastException cce) {
super.setColumnMatrix(column, matrix);
}
}
/**
* Sets the entries in column number {@code column}
* as a column matrix. Column indices start at 0.
*
* @param column Column to be set.
* @param matrix Column matrix (must have one column and the same number of rows
* as the instance).
* @throws MatrixDimensionMismatchException if the matrix dimensions do
* not match one instance column.
* @throws OutOfRangeException if the specified column index is invalid.
*/
void setColumnMatrix(final int column, final BlockFieldMatrix<T> matrix)
throws MatrixDimensionMismatchException, OutOfRangeException {
checkColumnIndex(column);
final int nRows = getRowDimension();
if ((matrix.getRowDimension() != nRows) ||
(matrix.getColumnDimension() != 1)) {
throw new MatrixDimensionMismatchException(matrix.getRowDimension(),
matrix.getColumnDimension(),
nRows, 1);
}
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int mBlockIndex = 0;
int mIndex = 0;
T[] mBlock = matrix.blocks[mBlockIndex];
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final T[] block = blocks[iBlock *
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>];
System.arraycopy(block, iRow * jWidth, out, outIndex, jWidth);
outIndex += jWidth;
}
return out;
}
/** {@inheritDoc} */
@Override
public void setRow(final int row, final T[] array)
throws OutOfRangeException, MatrixDimensionMismatchException {
checkRowIndex(row);
final int nCols = getColumnDimension();
if (array.length != nCols) {
throw new MatrixDimensionMismatchException(1, array.length, 1, nCols);
}
// perform copy block-wise, to ensure good cache behavior
final int iBlock = row / BLOCK_SIZE;
final int iRow = row - iBlock * BLOCK_SIZE;
int outIndex = 0;
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final T[] block = blocks[iBlock * blockColumns + jBlock];
System.arraycopy(array, outIndex, block, iRow * jWidth, jWidth);
outIndex += jWidth;
}
}
/** {@inheritDoc} */
@Override
public T[] getColumn(final int column) throws OutOfRangeException {
checkColumnIndex(column);
final T[] out = buildArray(getField(), rows);
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final T[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
out[outIndex++] = block[i * jWidth + jColumn];
}
}
return out;
}
/** {@inheritDoc} */
@Override
public void setColumn(final int column, final T[] array)
throws MatrixDimensionMismatchException, OutOfRangeException {
checkColumnIndex(column);
final int nRows = getRowDimension();
if (array.length != nRows) {
throw new MatrixDimensionMismatchException(array.length, 1, nRows, 1);
}
// perform copy block-wise, to ensure good cache behavior
final int jBlock = column / BLOCK_SIZE;
final int jColumn = column - jBlock * BLOCK_SIZE;
final int jWidth = blockWidth(jBlock);
int outIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int iHeight = blockHeight(iBlock);
final T[] block = blocks[iBlock * blockColumns + jBlock];
for (int i = 0; i < iHeight; ++i) {
block[i * jWidth + jColumn] = array[outIndex++];
}
}
}
/** {@inheritDoc} */
@Override
public T getEntry(final int row, final int column)
throws OutOfRangeException {
checkRowIndex(row);
checkColumnIndex(column);
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
return blocks[iBlock * blockColumns + jBlock][k];
}
/**
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> {@inheritDoc} */
@Override
public void setEntry(final int row, final int column, final T value)
throws OutOfRangeException {
checkRowIndex(row);
checkColumnIndex(column);
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
blocks[iBlock * blockColumns + jBlock][k] = value;
}
/** {@inheritDoc} */
@Override
public void addToEntry(final int row, final int column, final T increment)
throws OutOfRangeException {
checkRowIndex(row);
checkColumnIndex(column);
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
final T[] blockIJ = blocks[iBlock * blockColumns + jBlock];
blockIJ[k] = blockIJ[k].add(increment);
}
/** {@inheritDoc} */
@Override
public void multiplyEntry(final int row, final int column, final T factor)
throws OutOfRangeException {
checkRowIndex(row);
checkColumnIndex(column);
final int iBlock = row / BLOCK_SIZE;
final int jBlock = column / BLOCK_SIZE;
final int k = (row - iBlock * BLOCK_SIZE) * blockWidth(jBlock) +
(column - jBlock * BLOCK_SIZE);
final T[] blockIJ = blocks[iBlock * blockColumns + jBlock];
blockIJ[k] = blockIJ[k].multiply(factor);
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> transpose() {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
final BlockFieldMatrix<T> out = new BlockFieldMatrix<T>(getField(), nCols, nRows);
// perform transpose block-wise, to ensure good cache behavior
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockColumns; ++iBlock) {
for (int jBlock = 0; jBlock < blockRows; ++jBlock) {
// transpose current block
final T[] outBlock = out.blocks[blockIndex];
final T[] tBlock = blocks[jBlock * blockColumns + iBlock];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, columns);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, rows);
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
final int lInc = pEnd - pStart;
int l = p - pStart;
for (int q = qStart; q < qEnd; ++q) {
outBlock[k] = tBlock[l];
++k;
l+= lInc;
}
}
// go to next block
++blockIndex;
}
}
return out;
}
/** {@inheritDoc} */
@Override
public int getRowDimension() {
return rows;
}
/** {@inheritDoc} */
@Override
public int getColumnDimension() {
return columns;
}
/** {@inheritDoc} */
@Override
public T[] operate(
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>final T[] v) throws DimensionMismatchException {
if (v.length != columns) {
throw new DimensionMismatchException(v.length, columns);
}
final T[] out = buildArray(getField(), rows);
final T zero = getField().getZero();
// perform multiplication block-wise, to ensure good cache behavior
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final T[] block = blocks[iBlock * blockColumns + jBlock];
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
T sum = zero;
int q = qStart;
while (q < qEnd - 3) {
sum = sum.
add(block[k].multiply(v[q])).
add(block[k + 1].multiply(v[q + 1])).
add(block[k + 2].multiply(v[q + 2])).
add(block[k + 3].multiply(v[q + 3]));
k += 4;
q += 4;
}
while (q < qEnd) {
sum = sum.add(block[k++].multiply(v[q++]));
}
out[p] = out[p].add(sum);
}
}
}
return out;
}
/** {@inheritDoc} */
@Override
public T[] preMultiply(final T[] v) throws DimensionMismatchException {
if (v.length != rows) {
throw new DimensionMismatchException(v.length, rows);
}
final T[] out = buildArray(getField(), columns);
final T zero = getField().getZero();
// perform multiplication block-wise, to ensure good cache behavior
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int jWidth2 = jWidth + jWidth;
final int jWidth3 = jWidth2 + jWidth;
final int jWidth4 = jWidth3 + jWidth;
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final T[] block = blocks[iBlock * blockColumns + jBlock];
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int q = qStart; q < qEnd; ++q) {
int k = q - qStart;
T sum = zero;
int p = pStart;
while (p < pEnd - 3) {
sum = sum.
add(block[k].multiply(v[p])).
add(block[k + jWidth].multiply(v[p + 1])).
add(block[k + jWidth2].multiply(v[p + 2])).
add(block[k + jWidth3].multiply(v[p + 3]));
k += jWidth4;
p += 4;
}
while (p < pEnd) {
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> sum = sum.add(block[k].multiply(v[p++]));
k += jWidth;
}
out[q] = out[q].add(sum);
}
}
}
return out;
}
/** {@inheritDoc} */
@Override
public T walkInRowOrder(final FieldMatrixChangingVisitor<T> visitor) {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final T[] block = blocks[iBlock * blockColumns + jBlock];
int k = (p - pStart) * jWidth;
for (int q = qStart; q < qEnd; ++q) {
block[k] = visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInRowOrder(final FieldMatrixPreservingVisitor<T> visitor) {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final T[] block = blocks[iBlock * blockColumns + jBlock];
int k = (p - pStart) * jWidth;
for (int q = qStart; q < qEnd; ++q) {
visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInRowOrder(final FieldMatrixChangingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = FastMath.max(startRow, p0);
final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = FastMath.max(startColumn, q0);
final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final T[] block = blocks[iBlock * blockColumns + jBlock];
int k = (p - p0) * jWidth + qStart - q0;
for (int q = qStart; q < qEnd; ++q) {
block[k] = visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInRowOrder(final FieldMatrixPreservingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = FastMath.max(startRow, p0);
final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int p = pStart; p < pEnd; ++p) {
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = FastMath.max(startColumn, q0);
final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final T[] block = blocks[iBlock * blockColumns + jBlock];
int k = (p - p0) * jWidth + qStart - q0;
for (int q = qStart; q < qEnd; ++q) {
visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInOptimizedOrder(final FieldMatrixChangingVisitor<T> visitor) {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final T[] block = blocks[blockIndex];
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q) {
block[
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>k] = visitor.visit(p, q, block[k]);
++k;
}
}
++blockIndex;
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInOptimizedOrder(final FieldMatrixPreservingVisitor<T> visitor) {
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
int blockIndex = 0;
for (int iBlock = 0; iBlock < blockRows; ++iBlock) {
final int pStart = iBlock * BLOCK_SIZE;
final int pEnd = FastMath.min(pStart + BLOCK_SIZE, rows);
for (int jBlock = 0; jBlock < blockColumns; ++jBlock) {
final int qStart = jBlock * BLOCK_SIZE;
final int qEnd = FastMath.min(qStart + BLOCK_SIZE, columns);
final T[] block = blocks[blockIndex];
int k = 0;
for (int p = pStart; p < pEnd; ++p) {
for (int q = qStart; q < qEnd; ++q) {
visitor.visit(p, q, block[k]);
++k;
}
}
++blockIndex;
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInOptimizedOrder(final FieldMatrixChangingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock = startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = FastMath.max(startRow, p0);
final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = FastMath.max(startColumn, q0);
final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final T[] block = blocks[iBlock * blockColumns + jBlock];
for (int p = pStart; p < pEnd; ++p) {
int k = (p - p0) * jWidth + qStart - q0;
for (int q = qStart; q < qEnd; ++q) {
block[k] = visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInOptimizedOrder(final FieldMatrixPreservingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(rows, columns, startRow, endRow, startColumn, endColumn);
for (int iBlock =
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> startRow / BLOCK_SIZE; iBlock < 1 + endRow / BLOCK_SIZE; ++iBlock) {
final int p0 = iBlock * BLOCK_SIZE;
final int pStart = FastMath.max(startRow, p0);
final int pEnd = FastMath.min((iBlock + 1) * BLOCK_SIZE, 1 + endRow);
for (int jBlock = startColumn / BLOCK_SIZE; jBlock < 1 + endColumn / BLOCK_SIZE; ++jBlock) {
final int jWidth = blockWidth(jBlock);
final int q0 = jBlock * BLOCK_SIZE;
final int qStart = FastMath.max(startColumn, q0);
final int qEnd = FastMath.min((jBlock + 1) * BLOCK_SIZE, 1 + endColumn);
final T[] block = blocks[iBlock * blockColumns + jBlock];
for (int p = pStart; p < pEnd; ++p) {
int k = (p - p0) * jWidth + qStart - q0;
for (int q = qStart; q < qEnd; ++q) {
visitor.visit(p, q, block[k]);
++k;
}
}
}
}
return visitor.end();
}
/**
* Get the height of a block.
* @param blockRow row index (in block sense) of the block
* @return height (number of rows) of the block
*/
private int blockHeight(final int blockRow) {
return (blockRow == blockRows - 1) ? rows - blockRow * BLOCK_SIZE : BLOCK_SIZE;
}
/**
* Get the width of a block.
* @param blockColumn column index (in block sense) of the block
* @return width (number of columns) of the block
*/
private int blockWidth(final int blockColumn) {
return (blockColumn == blockColumns - 1) ? columns - blockColumn * BLOCK_SIZE : BLOCK_SIZE;
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>, MatrixDimensionMismatchException;
/**
* Get the entries at the given row index. Row indices start at 0.
*
* @param row Row to be fetched.
* @return the array of entries in the row.
* @throws OutOfRangeException if the specified row index is not valid.
*/
double[] getRow(int row) throws OutOfRangeException;
/**
* Sets the specified {@code row} of {@code this} matrix to the entries
* of the specified {@code array}. Row indices start at 0.
*
* @param row Row to be set.
* @param array Row matrix to be copied (must have the same number of
* columns as the instance)
* @throws OutOfRangeException if the specified row index is invalid.
* @throws MatrixDimensionMismatchException if the {@code array} length does
* not match the column dimension of {@code this} matrix.
*/
void setRow(int row, double[] array)
throws OutOfRangeException, MatrixDimensionMismatchException;
/**
* Get the entries at the given column index as an array. Column indices
* start at 0.
*
* @param column Column to be fetched.
* @return the array of entries in the column.
* @throws OutOfRangeException if the specified column index is not valid.
*/
double[] getColumn(int column) throws OutOfRangeException;
/**
* Sets the specified {@code column} of {@code this} matrix to the entries
* of the specified {@code array}. Column indices start at 0.
*
* @param column Column to be set.
* @param array Column array to be copied (must have the same number of
* rows as the instance).
* @throws OutOfRangeException if the specified column index is invalid.
* @throws MatrixDimensionMismatchException if the {@code array} length does
* not match the row dimension of {@code this} matrix.
*/
void setColumn(int column, double[] array)
throws OutOfRangeException, MatrixDimensionMismatchException;
/**
* Get the entry in the specified row and column. Row and column indices
* start at 0.
*
* @param row Row index of entry to be fetched.
* @param column Column index of entry to be fetched.
* @return the matrix entry at {@code (row, column)}.
* @throws OutOfRangeException if the row or column index is not valid.
*/
double getEntry(int row, int column) throws OutOfRangeException;
/**
* Set the entry in the specified row and column. Row and column indices
* start at 0.
*
* @param row Row index of entry to be set.
* @param column Column index of entry to be set.
* @param value the new value of the entry.
* @throws OutOfRangeException if the row or column index is not valid
* @since 2.0
*/
void setEntry(int row, int column, double value) throws OutOfRangeException;
/**
* Adds (in place) the specified value to the specified entry of
* {@code this} matrix. Row and column indices start at 0.
*
* @param row Row index of the entry to be modified.
* @param column Column index of the entry to be modified.
* @param increment value to add to the matrix entry.
* @throws OutOfRangeException if the row or column index is not valid.
* @since 2.0
*/
void addToEntry(int row, int column, double increment) throws OutOfRangeException;
/**
* Multiplies (in place) the specified entry of {@code this} matrix by the
* specified value. Row
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>.
* @throws OutOfRangeException if the specified row index is not valid.
*/
T[] getRow(int row) throws OutOfRangeException;
/**
* Set the entries in row number {@code row}
* as a row matrix.
*
* @param row Row to be set.
* @param array Row matrix (must have the same number of columns as
* the instance).
* @throws OutOfRangeException if the specified row index is invalid.
* @throws MatrixDimensionMismatchException if the array size does not match
* one instance row.
*/
void setRow(int row, T[] array) throws MatrixDimensionMismatchException,
OutOfRangeException;
/**
* Get the entries in column number {@code col} as an array.
*
* @param column the column to be fetched
* @return array of entries in the column
* @throws OutOfRangeException if the specified column index is not valid.
*/
T[] getColumn(int column) throws OutOfRangeException;
/**
* Set the entries in column number {@code column}
* as a column matrix.
*
* @param column the column to be set
* @param array column array (must have the same number of rows as the instance)
* @throws OutOfRangeException if the specified column index is invalid.
* @throws MatrixDimensionMismatchException if the array size does not match
* one instance column.
*/
void setColumn(int column, T[] array) throws MatrixDimensionMismatchException,
OutOfRangeException;
/**
* Returns the entry in the specified row and column.
*
* @param row row location of entry to be fetched
* @param column column location of entry to be fetched
* @return matrix entry in row,column
* @throws OutOfRangeException if the row or column index is not valid.
*/
T getEntry(int row, int column) throws OutOfRangeException;
/**
* Set the entry in the specified row and column.
*
* @param row row location of entry to be set
* @param column column location of entry to be set
* @param value matrix entry to be set in row,column
* @throws OutOfRangeException if the row or column index is not valid.
* @since 2.0
*/
void setEntry(int row, int column, T value) throws OutOfRangeException;
/**
* Change an entry in the specified row and column.
*
* @param row Row location of entry to be set.
* @param column Column location of entry to be set.
* @param increment Value to add to the current matrix entry in
* {@code (row, column)}.
* @throws OutOfRangeException if the row or column index is not valid.
* @since 2.0
*/
void addToEntry(int row, int column, T increment) throws OutOfRangeException;
/**
* Change an entry in the specified row and column.
*
* @param row Row location of entry to be set.
* @param column Column location of entry to be set.
* @param factor Multiplication factor for the current matrix entry
* in {@code (row,column)}
* @throws OutOfRangeException if the row or column index is not valid.
* @since 2.0
*/
void multiplyEntry(int row, int column, T factor) throws OutOfRangeException;
/**
* Returns the transpose of this matrix.
*
* @return transpose matrix
*/
FieldMatrix<T> transpose();
/**
* Returns the <a href="http://mathworld.wolfram.com/MatrixTrace.html">
* trace</a> of the matrix
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>[])
*/
public Array2DRowFieldMatrix(final Field<T> field, final T[][] d, final boolean copyArray)
throws DimensionMismatchException, NoDataException, NullArgumentException {
super(field);
if (copyArray) {
copyIn(d);
} else {
MathUtils.checkNotNull(d);
final int nRows = d.length;
if (nRows == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW);
}
final int nCols = d[0].length;
if (nCols == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
for (int r = 1; r < nRows; r++) {
if (d[r].length != nCols) {
throw new DimensionMismatchException(nCols, d[r].length);
}
}
data = d;
}
}
/**
* Create a new (column) {@code FieldMatrix<T>} using {@code v} as the
* data for the unique column of the created matrix.
* The input array is copied.
*
* @param v Column vector holding data for new matrix.
* @throws NoDataException if v is empty
*/
public Array2DRowFieldMatrix(final T[] v) throws NoDataException {
this(extractField(v), v);
}
/**
* Create a new (column) {@code FieldMatrix<T>} using {@code v} as the
* data for the unique column of the created matrix.
* The input array is copied.
*
* @param field Field to which the elements belong.
* @param v Column vector holding data for new matrix.
*/
public Array2DRowFieldMatrix(final Field<T> field, final T[] v) {
super(field);
final int nRows = v.length;
data = buildArray(getField(), nRows, 1);
for (int row = 0; row < nRows; row++) {
data[row][0] = v[row];
}
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> createMatrix(final int rowDimension,
final int columnDimension)
throws NotStrictlyPositiveException {
return new Array2DRowFieldMatrix<T>(getField(), rowDimension, columnDimension);
}
/** {@inheritDoc} */
@Override
public FieldMatrix<T> copy() {
return new Array2DRowFieldMatrix<T>(getField(), copyOut(), false);
}
/**
* Add {@code m} to this matrix.
*
* @param m Matrix to be added.
* @return {@code this} + m.
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as this matrix.
*/
public Array2DRowFieldMatrix<T> add(final Array2DRowFieldMatrix<T> m)
throws MatrixDimensionMismatchException {
// safety check
checkAdditionCompatible(m);
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final T[][] outData = buildArray(getField(), rowCount, columnCount);
for (int row = 0; row < rowCount; row++) {
final T[] dataRow = data[row];
final T[] mRow = m.data[row];
final T[] outDataRow = outData[row];
for (int col = 0; col < columnCount; col++) {
outDataRow[col] = dataRow[col].add(mRow[col]);
}
}
return new Array2DRowFieldMatrix<T>(getField(), out
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Data, false);
}
/**
* Subtract {@code m} from this matrix.
*
* @param m Matrix to be subtracted.
* @return {@code this} + m.
* @throws MatrixDimensionMismatchException if {@code m} is not the same
* size as this matrix.
*/
public Array2DRowFieldMatrix<T> subtract(final Array2DRowFieldMatrix<T> m)
throws MatrixDimensionMismatchException {
// safety check
checkSubtractionCompatible(m);
final int rowCount = getRowDimension();
final int columnCount = getColumnDimension();
final T[][] outData = buildArray(getField(), rowCount, columnCount);
for (int row = 0; row < rowCount; row++) {
final T[] dataRow = data[row];
final T[] mRow = m.data[row];
final T[] outDataRow = outData[row];
for (int col = 0; col < columnCount; col++) {
outDataRow[col] = dataRow[col].subtract(mRow[col]);
}
}
return new Array2DRowFieldMatrix<T>(getField(), outData, false);
}
/**
* Postmultiplying this matrix by {@code m}.
*
* @param m Matrix to postmultiply by.
* @return {@code this} * m.
* @throws DimensionMismatchException if the number of columns of this
* matrix is not equal to the number of rows of {@code m}.
*/
public Array2DRowFieldMatrix<T> multiply(final Array2DRowFieldMatrix<T> m)
throws DimensionMismatchException {
// safety check
checkMultiplicationCompatible(m);
final int nRows = this.getRowDimension();
final int nCols = m.getColumnDimension();
final int nSum = this.getColumnDimension();
final T[][] outData = buildArray(getField(), nRows, nCols);
for (int row = 0; row < nRows; row++) {
final T[] dataRow = data[row];
final T[] outDataRow = outData[row];
for (int col = 0; col < nCols; col++) {
T sum = getField().getZero();
for (int i = 0; i < nSum; i++) {
sum = sum.add(dataRow[i].multiply(m.data[i][col]));
}
outDataRow[col] = sum;
}
}
return new Array2DRowFieldMatrix<T>(getField(), outData, false);
}
/** {@inheritDoc} */
@Override
public T[][] getData() {
return copyOut();
}
/**
* Get a reference to the underlying data array.
* This methods returns internal data, <strong>not</strong> fresh copy of it.
*
* @return the 2-dimensional array of entries.
*/
public T[][] getDataRef() {
return data;
}
/** {@inheritDoc} */
@Override
public void setSubMatrix(final T[][] subMatrix, final int row,
final int column)
throws OutOfRangeException, NullArgumentException, NoDataException,
DimensionMismatchException {
if (data == null) {
if (row > 0) {
throw new MathIllegalStateException(LocalizedFormats.FIRST_ROWS_NOT_INITIALIZED_YET, row);
}
if (column > 0) {
throw new MathIllegalStateException(LocalizedFormats.FIRST_COLUMNS_NOT_INITIALIZED_YET, column);
}
final int nRows = subMatrix.length;
if (nRows == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_ROW
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>);
}
final int nCols = subMatrix[0].length;
if (nCols == 0) {
throw new NoDataException(LocalizedFormats.AT_LEAST_ONE_COLUMN);
}
data = buildArray(getField(), subMatrix.length, nCols);
for (int i = 0; i < data.length; ++i) {
if (subMatrix[i].length != nCols) {
throw new DimensionMismatchException(nCols, subMatrix[i].length);
}
System.arraycopy(subMatrix[i], 0, data[i + row], column, nCols);
}
} else {
super.setSubMatrix(subMatrix, row, column);
}
}
/** {@inheritDoc} */
@Override
public T getEntry(final int row, final int column)
throws OutOfRangeException {
checkRowIndex(row);
checkColumnIndex(column);
return data[row][column];
}
/** {@inheritDoc} */
@Override
public void setEntry(final int row, final int column, final T value)
throws OutOfRangeException {
checkRowIndex(row);
checkColumnIndex(column);
data[row][column] = value;
}
/** {@inheritDoc} */
@Override
public void addToEntry(final int row, final int column, final T increment)
throws OutOfRangeException {
checkRowIndex(row);
checkColumnIndex(column);
data[row][column] = data[row][column].add(increment);
}
/** {@inheritDoc} */
@Override
public void multiplyEntry(final int row, final int column, final T factor)
throws OutOfRangeException {
checkRowIndex(row);
checkColumnIndex(column);
data[row][column] = data[row][column].multiply(factor);
}
/** {@inheritDoc} */
@Override
public int getRowDimension() {
return (data == null) ? 0 : data.length;
}
/** {@inheritDoc} */
@Override
public int getColumnDimension() {
return ((data == null) || (data[0] == null)) ? 0 : data[0].length;
}
/** {@inheritDoc} */
@Override
public T[] operate(final T[] v) throws DimensionMismatchException {
final int nRows = this.getRowDimension();
final int nCols = this.getColumnDimension();
if (v.length != nCols) {
throw new DimensionMismatchException(v.length, nCols);
}
final T[] out = buildArray(getField(), nRows);
for (int row = 0; row < nRows; row++) {
final T[] dataRow = data[row];
T sum = getField().getZero();
for (int i = 0; i < nCols; i++) {
sum = sum.add(dataRow[i].multiply(v[i]));
}
out[row] = sum;
}
return out;
}
/** {@inheritDoc} */
@Override
public T[] preMultiply(final T[] v) throws DimensionMismatchException {
final int nRows = getRowDimension();
final int nCols = getColumnDimension();
if (v.length != nRows) {
throw new DimensionMismatchException(v.length, nRows);
}
final T[] out = buildArray(getField(), nCols);
for (int col = 0; col < nCols; ++col) {
T sum = getField().getZero();
for (int i = 0; i < nRows; ++i) {
sum = sum.add(data[i][col].multiply(v[i]));
}
out[col]
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS> = sum;
}
return out;
}
/** {@inheritDoc} */
@Override
public T walkInRowOrder(final FieldMatrixChangingVisitor<T> visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int i = 0; i < rows; ++i) {
final T[] rowI = data[i];
for (int j = 0; j < columns; ++j) {
rowI[j] = visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInRowOrder(final FieldMatrixPreservingVisitor<T> visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int i = 0; i < rows; ++i) {
final T[] rowI = data[i];
for (int j = 0; j < columns; ++j) {
visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInRowOrder(final FieldMatrixChangingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int i = startRow; i <= endRow; ++i) {
final T[] rowI = data[i];
for (int j = startColumn; j <= endColumn; ++j) {
rowI[j] = visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInRowOrder(final FieldMatrixPreservingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int i = startRow; i <= endRow; ++i) {
final T[] rowI = data[i];
for (int j = startColumn; j <= endColumn; ++j) {
visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInColumnOrder(final FieldMatrixChangingVisitor<T> visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int j = 0; j < columns; ++j) {
for (int i = 0; i < rows; ++i) {
final T[] rowI = data[i];
rowI[j] = visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>Override
public T walkInColumnOrder(final FieldMatrixPreservingVisitor<T> visitor) {
final int rows = getRowDimension();
final int columns = getColumnDimension();
visitor.start(rows, columns, 0, rows - 1, 0, columns - 1);
for (int j = 0; j < columns; ++j) {
for (int i = 0; i < rows; ++i) {
visitor.visit(i, j, data[i][j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInColumnOrder(final FieldMatrixChangingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int j = startColumn; j <= endColumn; ++j) {
for (int i = startRow; i <= endRow; ++i) {
final T[] rowI = data[i];
rowI[j] = visitor.visit(i, j, rowI[j]);
}
}
return visitor.end();
}
/** {@inheritDoc} */
@Override
public T walkInColumnOrder(final FieldMatrixPreservingVisitor<T> visitor,
final int startRow, final int endRow,
final int startColumn, final int endColumn)
throws OutOfRangeException, NumberIsTooSmallException {
checkSubMatrixIndex(startRow, endRow, startColumn, endColumn);
visitor.start(getRowDimension(), getColumnDimension(),
startRow, endRow, startColumn, endColumn);
for (int j = startColumn; j <= endColumn; ++j) {
for (int i = startRow; i <= endRow; ++i) {
visitor.visit(i, j, data[i][j]);
}
}
return visitor.end();
}
/**
* Get a fresh copy of the underlying data array.
*
* @return a copy of the underlying data array.
*/
private T[][] copyOut() {
final int nRows = this.getRowDimension();
final T[][] out = buildArray(getField(), nRows, getColumnDimension());
// can't copy 2-d array in one shot, otherwise get row references
for (int i = 0; i < nRows; i++) {
System.arraycopy(data[i], 0, out[i], 0, data[i].length);
}
return out;
}
/**
* Replace data with a fresh copy of the input array.
*
* @param in Data to copy.
* @throws NoDataException if the input array is empty.
* @throws DimensionMismatchException if the input array is not rectangular.
* @throws NullArgumentException if the input array is {@code null}.
*/
private void copyIn(final T[][] in)
throws NullArgumentException, NoDataException,
DimensionMismatchException {
setSubMatrix(in, 0, 0);
}
}
Math, 13
<FILEB>
<CHANGES>
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
<CHANGEE>
<CHANGES>
}
<CHANGEE>
<FILEE>
<FILEB>
final double[] target = getTarget();
if (objectiveValue.length != target.length) {
throw new DimensionMismatchException(target.length,
objectiveValue.length);
}
final double[] residuals = new double[target.length];
for (int i = 0; i < target.length; i++) {
residuals[i] = target[i] - objectiveValue[i];
}
return residuals;
}
/**
* Computes the square-root of the weight matrix.
*
* @param m Symmetric, positive-definite (weight) matrix.
* @return the square-root of the weight matrix.
*/
private RealMatrix squareRoot(RealMatrix m) {
<CHANGES>
<CHANGEE>
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
<CHANGES>
<CHANGEE>
}
}
<FILEE>
<SCANS>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.optimization;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.DiagonalMatrix;
import org.apache.commons.math3.linear.NonSquareMatrixException;
/**
* Weight matrix of the residuals between model and observations.
* <br/>
* Immutable class.
*
* @version $Id$
* @deprecated As of 3.1 (to be removed in 4.0).
* @since 3.1
*/
@Deprecated
public class Weight implements OptimizationData {
/** Weight matrix. */
private final RealMatrix weightMatrix;
/**
* Creates a diagonal weight matrix.
*
* @param weight List of the values of the diagonal.
*/
public Weight(double[] weight) {
weightMatrix = new DiagonalMatrix(weight);
}
/**
* @param weight Weight matrix.
* @throws NonSquareMatrixException if the argument is not
* a square matrix.
*/
public Weight(RealMatrix weight) {
if (weight.getColumnDimension() != weight.getRowDimension()) {
throw new NonSquareMatrixException(weight.getColumnDimension(),
weight.getRowDimension());
}
weightMatrix = weight.copy();
}
/**
* Gets the initial guess.
*
* @return the initial guess.
*/
public RealMatrix getWeight() {
return weightMatrix.copy();
}
}